0

我正在使用以下代码来增加围绕给定元素的二维数组中的元素。

 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++运行时,整个数组中的每个元素都会递增。有人可以解释为什么会这样吗?

4

1 回答 1

10

EmptyCell是一个对象,所以所有元素都引用同一个对象。如果要为每个元素使用单独的对象,请每次创建一个新实例。

于 2009-10-26T23:20:42.347 回答