我使用以下代码来增加围绕给定元素的二维数组中的元素。
EmptyCell = {number: 0}; //This has several parts in the actual code.
list = new Array();
function init(w,h){
for (var x = 0; x <= w; x++){
list[x] = new Array();
for (var y = 0 ; y <= h; y++){
list[x][y] = EmptyCell;
}
}
}
function map(func,x,y){
var xoff = [1,1,1,0,0,-1,-1,-1];
var yoff = [1,0,-1,1,-1,1,0,-1];
for (var atIndex = 0; atIndex < 8; atIndex++){
func(x+xoff[atIndex],y+yoff[atIndex]);
}
}
然后我按照这样运行:
init(10,10);
map(function(x,y){
if (list[x] != null && list[x][y] != null){
list[x][y].number++;
}
},0,0);
每次运行list[x][y].number++
时,整个数组中的每个元素都会递增。
有人可以解释为什么会这样吗?
答案 0 :(得分:10)
EmptyCell
是一个对象,因此所有元素都引用同一个对象。如果要为每个元素使用单独的对象,请每次都创建一个新实例。