当只有一个元素时,数组中的每个元素都会同时递增

Gam*_*eak 0 javascript arrays anonymous-function

我使用以下代码来增加围绕给定元素的2d数组中的元素.

 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]);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我像这样运行它:

init(10,10);

map(function(x,y){
    if (list[x] != null && list[x][y] != null){
        list[x][y].number++;
    }
},0,0);
Run Code Online (Sandbox Code Playgroud)

每次list[x][y].number++运行时,整个数组中的每个元素都会递增.有人可以解释为什么会这样吗?

rec*_*ive 10

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