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循环中用键值对填充它
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.
谢谢。
2 个解决方案
#1
5
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);
}
#2
6
Use 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
有关方括号表示法的更多信息,请查看此处
#1
5
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);
}
#2
6
Use 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
有关方括号表示法的更多信息,请查看此处