admin管理员组文章数量:1328015
I'd like to create this object...
object = {
'object[1][var_name_1]' : 'value1',
'object[1][var_name_2]' : 'value2',
};
I'm trying to it this way, but I'm getting error missing : after property id...
function getPrefix() {
return 'object[1]';
}
object = {
getPrefix() + '[var_name_1]' : 'value1',
getPrefix() + '[var_name_2]' : 'value2',
}
What am I doing wrong? Or maybbe it is impossible to set object property name using js experession?
Thank you
I'd like to create this object...
object = {
'object[1][var_name_1]' : 'value1',
'object[1][var_name_2]' : 'value2',
};
I'm trying to it this way, but I'm getting error missing : after property id...
function getPrefix() {
return 'object[1]';
}
object = {
getPrefix() + '[var_name_1]' : 'value1',
getPrefix() + '[var_name_2]' : 'value2',
}
What am I doing wrong? Or maybbe it is impossible to set object property name using js experession?
Thank you
Share Improve this question asked May 18, 2010 at 8:09 KirzillaKirzilla 16.6k27 gold badges89 silver badges131 bronze badges 1- 1 possible duplicate of Using a variable for a Javascript object key – Bergi Commented Apr 15, 2013 at 0:18
2 Answers
Reset to default 5You cant set variable properties using literal syntax, but you can set properties using []
, after you've created the object:
myObject = {}
myObject["any_string_here"] = myValue
In an object literal, each property name can only be identifier rather than an expression, which means you can't use variables. You can only use the square bracket notation on an existing object, so if you have a variable you wish to use as a property name then you'll need to do it after the object is created:
var object = {
'1': {};
};
object[1][var_name_1] = 'value1';
object[1][var_name_2] = 'value2';
本文标签: Javascript expression to define object39s property nameStack Overflow
版权声明:本文标题:Javascript expression to define object's property name? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742243454a2438978.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论