开发者

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

开发者 https://www.devze.com 2022-12-09 17:52 出处:网络
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.

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开发者_JAVA技巧);

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号