简体   繁体   中英

Every element in an array being incremented simultaneously when only one should be

I am using the following code to increment the elements in a 2d array surrounding a given element.

 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]);
    }
}

And then I run it like this:

init(10,10);

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

Each time list[x][y].number++ is run, every element in the entire array is incremented. Could somebody explain why this is happening?

EmptyCell is an object, so all the elements reference the same object. If you want to use separate objects for each element, create a new instance each time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM