开发者

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++) {开发者_JAVA技巧
    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?


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


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


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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜