admin管理员组文章数量:1317910
So I have this plain object
var data = {};
And i want to fill it with key-value pairs in a for loop like this
for(var i=0; i<n; i++){
$.extend(
data,
{
'a'+toString(i): someFunction(i),
'b'+toString(i): someFunction(i)
};
);
};
but seems like it's impossible to concatenate strings when defining the key. Is there any neat way to do what I need, because I feel like my approach is lame from the very begining.
Thanks.
So I have this plain object
var data = {};
And i want to fill it with key-value pairs in a for loop like this
for(var i=0; i<n; i++){
$.extend(
data,
{
'a'+toString(i): someFunction(i),
'b'+toString(i): someFunction(i)
};
);
};
but seems like it's impossible to concatenate strings when defining the key. Is there any neat way to do what I need, because I feel like my approach is lame from the very begining.
Thanks.
Share Improve this question edited Dec 5, 2014 at 11:00 Mark Walters 12.4k6 gold badges35 silver badges48 bronze badges asked Feb 26, 2014 at 16:42 yur15tyur15t 3171 gold badge5 silver badges15 bronze badges 1-
'a'+toString(i)
doesn't do what you think it does. – georg Commented Feb 26, 2014 at 16:59
2 Answers
Reset to default 7Use this syntax
for ( var i = 0; i < n; i++ ) {
data['a'+toString(i)] = someFunction(i);
}
To use a non-literal key with an object you need to use the square bracket notation. This allows you to create dynamic keys.
Have a look here for more info on square bracket notation
You need to use bracket notation as the member operator since the keys are dynamic
for (var i = 0; i < n; i++) {
data['a' + toString(i)] = someFunction(i);
data['b' + toString(i)] = someFunction(i);
}
本文标签: javascriptConcatenate strings in key of plain objectStack Overflow
版权声明:本文标题:javascript - Concatenate strings in key of plain object - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742029060a2416100.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论