我想创建Object-type数组,for循环只推送最后一个值?
parse

结果:
答案 0 :(得分:1)
通过代码中的评论添加
var arr = [];
// removed object declaration
// removed initialization
a = [1, 2, 3, 4];
b = ['tom', 'sun', 'bob', 'kiki'];
for (var i = 0; i < 4; i++) {
// initialize new object
var k = {};
// set properties
k.num = a[i];
k.name = b[i];
arr.push(k)
}
console.log(arr)
//result [{name:'kiki',num:4},{name:'kiki',num:4},{name:'kiki',num:4},{name:'kiki',num:4}]
&#13;
var arr = [];
a = [1, 2, 3, 4];
b = ['tom', 'sun', 'bob', 'kiki'];
for (var i = 0, length = a.length; i < length; i++) {
arr.push({num: a[i], name: b[i]})
}
console.log(arr)
//result [{name:'kiki',num:4},{name:'kiki',num:4},{name:'kiki',num:4},{name:'kiki',num:4}]
&#13;