Max Wofford
Max Wofford

Reputation: 253

Selecting object in 2 dimensional arrays js

I've got a 2 dimensional array (I'll call it myArray). myArray is full of 10 child arrays, each with 10 "-"s.

function mapInit () {
    max_size = 10;
    board = [];

    map_width = Math.floor((Math.random() * max_size + max_size) / 2);
    map_height = Math.floor((Math.random() * max_size + max_size) / 2);

    boardsize = { x : map_width, y : map_height }
}

function generateBoard () {
    var columns = [];
    for (var i = 0; i < map_height; i++) {
        columns.push("---");
    };
    for (var i = 0; i < map_width; i++) {
        board.push(columns);
    };
}

When I select myArray[x][y], it returns the value of the single object in that array: "-". This makes sense because I asked for that individual value.

When I set myArray[x][y] = 1, it sets all [y] in the second-level arrays to 1. It should set the individual value in that specific child array to 1, because the individual value is what was just returned when I selected myArray[x][y]. What am I doing wrong / not understanding?

Upvotes: 0

Views: 54

Answers (1)

Felix Kling
Felix Kling

Reputation: 816760

What am I doing wrong / not understanding?

You adding a reference to a single array multiple times to another array. Take a look at this simplified example:

var a = [];
var b = [a, a];

a[0] = 42;
console.log(b);
// [[42], [42]]

as you can see, I'm setting a as the first and second element in the b array. There is no reason why this operation should create two copies of a in the process. Both elements reference the same array, which you can easily test with

b[0] === b[1] // true

Two distinct arrays would never be equal to each other ([] === [] returns false).


Solution: Create a copy of the array inside the second loop:

for (var i = 0; i < map_width; i++) {
    board.push(columns.slice(0));
}

Upvotes: 1

Related Questions