var initGrid = function() {
//creating a grid while initialising it
var grid = [];
// declaring each grid element as a Object having three properties
var gridElement = {
x: Number,
y: Number,
val: Number
};
for (var i = 0; i < 10; i++) {
for (var j = 0; j < 10; j++) {
gridElement.x = i;
gridElement.y = j;
gridElement.val = 0;
grid.push(gridElement);
};
};
return grid;
};
console.log(initGrid());
当我在控制台上运行此代码时,grid Array的所有Object的x和y值都相同,分别为9和9。
但是我想创建具有不同值的对象以循环变量
最佳答案
这是因为,对象是通过引用传递的。您将必须在每次迭代中创建不同的对象。
以下是示例。
var initGrid = function() {
//creating a grid while initialising it
var grid = [];
for (var i = 0; i < 10; i++) {
for (var j = 0; j < 10; j++) {
var gridElement = {}
gridElement.x = i;
gridElement.y = j;
gridElement.val = 0;
grid.push(gridElement);
};
};
return grid;
};
console.log(initGrid());