1

如何在 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]},
            ];
4

2 回答 2

4

括号符号:

for (var i = 0; i<= 8; i++){
  var obj = {};
  obj['name'+ i] = [0,0,0];
  myArray.push(obj);
}
于 2013-04-05T10:12:40.540 回答
1

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

var myArray = [];

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

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

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

    myArray.push(obj);

}
于 2013-04-05T10:12:21.140 回答