Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/393.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 数组中的每个元素同时递增,而只有一个元素应该递增_Javascript_Arrays_Anonymous Function - Fatal编程技术网

Javascript 数组中的每个元素同时递增,而只有一个元素应该递增

Javascript 数组中的每个元素同时递增,而只有一个元素应该递增,javascript,arrays,anonymous-function,Javascript,Arrays,Anonymous Function,我使用下面的代码来增加给定元素周围的二维数组中的元素 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++){

我使用下面的代码来增加给定元素周围的二维数组中的元素

 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]);
    }
}
每次运行
list[x][y].number++
时,整个数组中的每个元素都会递增。
有人能解释一下为什么会发生这种情况吗?

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

init(10,10);

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