要成功地将这些对象添加到数组中,您需要在 y.push() 语句上创建一个闭包。闭包将确保变量 x[i] 在调用时可用于 value() 函数。
The code below defines the 'addItem()' function which closes over the 'value()' function of the object creating a self contained environment. This means the 'value()' function will still have access to the variables defined or passed within the 'addItem()' function even after the 'addItem()' function has finished.
var i = 0
var y = [] ;
var x = [[1,2,3] , [4,5,6] , [7,8,9]];
function addItem(item) {
y.push({
name: 'MyName',
value: function () {
return item;
}
});
}
for ( ; i < 3 ; i++) {
addItem(x[i]);
}
console.log(y);
/*
[ { name: 'MyName', value: [Function] },
{ name: 'MyName', value: [Function] },
{ name: 'MyName', value: [Function] } ]
*/
console.log(y[0].value()); // [1, 2, 3]
console.log(y[1].value()); // [4, 5, 6]
console.log(y[2].value()); // [7, 8, 9]
You can also achieve the same thing using an anonymous function within the loop but I choose not to do this as that would have created a new function each time you went around the for loop.