将动态键:值对传递给对象文字? [英] Passing in dynamic key:value pairs to an object literal?
问题描述
我正在使用这段代码(如下所示)尝试在for循环中填充名为 Parameters
的对象文字。我需要键:值
对与迭代 i
变量的循环一起分配,如下: {key_1:组块[1],key_2:块[2]}
。但是,我的代码无效。 'key _'+ i
没有反映在文字中。
I am using this slice of code (shown below) in an attempt to populate the object literal named Parameters
inside the for loop. I need the key:value
pair to be assigned in conjunction with the loops iterating i
variable, as such: {key_1:chunks[1],key_2:chunks[2]}
. However, my code isn't working. The 'key_'+i
is not being reflected in the literal.
这里有一些我遗漏的东西,很明显。有人可以告诉我它是什么吗?...谢谢。
There's something I am missing here, obviously. Can someone tell me what it is?...Thanks.
var Parameters=[];
var len = chunks.length;
for (var i = 0; i < len; i++) {
var key='key_'+i
obj= { key : chunks[i]};
Parameters.push(obj)
}
推荐答案
编辑:使用 var obj = {}; obj [key] = chunks [i];
因为ECMAScript处理键
在此 {key:1}
中为字面值。
Because ECMAScript treats the key
in this {key:1}
as literal.
这篇关于将动态键:值对传递给对象文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!