选择二维数组js中的对象

时间:2014-10-07 16:32:26

标签: javascript arrays

我有一个二维数组(我称之为myArray)。 myArray包含10个子数组,每个数组都有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);
    };
}

当我选择myArray[x][y]时,它返回该数组中单个对象的值:&#34; - &#34;。这是有道理的,因为我要求个人价值。

当我设置myArray[x][y] = 1时,它将第二级数组中的所有[y]设置为1.它应该将该特定子数组中的单个值设置为1,因为单个值是刚刚返回的值当我选择myArray[x][y]时。我做错了什么/不理解?

1 个答案:

答案 0 :(得分:1)

  

我做错了什么/不理解?

您将对单个数组的引用多次添加到另一个数组。看看这个简化的例子:

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

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

如您所见,我将a设置为b数组中的第一个和第二个元素。这个操作没有理由在此过程中创建a的两个副本。两个元素都引用相同的数组,您可以使用

轻松测试
b[0] === b[1] // true

两个不同的数组永远不会彼此相等([] === []返回false)。


在第二个循环中

解决方案: Create a copy of the array

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