Pascal Bayer
Pascal Bayer

Reputation: 2613

Problem with JavaScript Array

TilesArray.tiles has a wrong output, alert(TilesArray.array); gives me the correct output with randomized numbers, but at the end TilesArray.tiles has the same array in each index.

for (i = 0; i < 200; i++) {
    for (j = 0; j < 200; j++) {
        TilesArray.array[j] = (Math.round(Math.random() * 499 + 1));
    }
    alert(TilesArray.array);
    TilesArray.tiles[i] = TilesArray.array;
}

Any solution to fix the issue?

Upvotes: -1

Views: 116

Answers (3)

JB Nizet
JB Nizet

Reputation: 692271

At each iteration, you fill your TilesArray.array with new random values, and store a reference to this unique array in TilesArray.tiles[i]. But the array of random values is always the same. You just have many pointers to the same array.

You need to allocate a new array at each iteration :

for (i = 0; i < 200; i++) {
    TilesArray.array = [];
    for (j = 0; j < 200; j++) {
        TilesArray.array[j] = (Math.round(Math.random() * 499 + 1));
    }
    alert(TilesArray.array);
    TilesArray.tiles[i] = TilesArray.array;
}

Upvotes: 1

David Tang
David Tang

Reputation: 93714

You're continuously adding a reference to the same array to tiles. To get around this, create a new array in each iteration of the outer loop:

for (i = 0; i < 200; i++) {
    TilesArray.array = []; // This is the line
    for (j = 0; j < 200; j++) {
        TilesArray.array[j] = (Math.round(Math.random() * 499 + 1));
    }
    alert(TilesArray.array);
    TilesArray.tiles[i] = TilesArray.array;
}

Or even better? Add everything directly to your tiles array (it's one less variable to worry about):

for (i = 0; i < 200; i++) {
    TilesArray.tiles[i] = [];
    for (j = 0; j < 200; j++) {
        TilesArray.tiles[i][j] = (Math.round(Math.random() * 499 + 1));
    }
}

Upvotes: 3

egze
egze

Reputation: 3236

You need to copy the array. Could be done with slice()

for (i = 0; i < 200; i++) {
    for (j = 0; j < 200; j++) {
        TilesArray.array[j] = (Math.round(Math.random() * 499 + 1));
    }
    alert(TilesArray.array);
    TilesArray.tiles[i] = TilesArray.array.slice(0);
}

Upvotes: 4

Related Questions