在for循环中设置自定义JSON对象名称

时间:2013-04-05 10:10:15

标签: javascript

如何在for循环中设置自定义JSON对象名称。

var myArray = [];

for (var i = 0; i<= 8; i++){

    var x = "name" + i;

    myArray.push({x:[0,0,0]});

}

我想要这个

myArray = [
            {name0:[0,0,0]},
            {name1:[0,0,0]},
            {name2:[0,0,0]},
            {name3:[0,0,0]},
            {name4:[0,0,0]},
            {name5:[0,0,0]},
            {name6:[0,0,0]},
            {name7:[0,0,0]},
            {name8:[0,0,0]},
            ];

但它会返回此

myArray = [
            {x:[0,0,0]},
            {x:[0,0,0]},
            {x:[0,0,0]},
            {x:[0,0,0]},
            {x:[0,0,0]},
            {x:[0,0,0]},
            {x:[0,0,0]},
            {x:[0,0,0]},
            {x:[0,0,0]},
            ];

2 个答案:

答案 0 :(得分:4)

括号表示法:

for (var i = 0; i<= 8; i++){
  var obj = {};
  obj['name'+ i] = [0,0,0];
  myArray.push(obj);
}

答案 1 :(得分:1)

要将变量用作对象中的键,应使用括号表示法:

var myArray = [];

for (var i = 0; i<= 8; i++){

    var x   = "name" + i,
        obj = {};

    obj[x] = [0,0,0];

    myArray.push(obj);

}