-1

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?

3 Answers 3

4

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Actually, I think there is another problem, the fact that Math.random() is not really random
3

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.