在2维数组JS选择对象 [英] Selecting object in 2 dimensional arrays js

查看:167
本文介绍了在2维数组JS选择对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经有了一个2维数组(我称之为 myArray的)。 myArray的满10孩子阵列,每10 - :S

 函数mapInit(){
    MAX_SIZE = 10;
    板= [];    地图宽度= Math.floor((的Math.random()* + MAX_SIZE MAX_SIZE)/ 2);
    地图高度= Math.floor((的Math.random()* + MAX_SIZE MAX_SIZE)/ 2);    boardsize = {X:地图宽度,Y:地图高度}
}功能generateBoard(){
    变种列= [];
    对于(VAR I = 0; I<地图高度,我++){
        columns.push(---);
    };
    对于(VAR I = 0; I<地图宽度;我++){
        board.push(列);
    };
}

当我选择 myArray的[X] [Y] ,它返回数组中的单个对象的值: - 。这是有道理的,因为我要的那种个人的价值。

当我设置 myArray的[X] [Y] = 1 ,它会将所有的[Y]在第二级阵列1,应设置单独的值在特定子阵列1,由于个人价值是,当我选择什么刚回到 myArray的[X] [Y] 。我在做什么错了/不理解?


解决方案

  

我是什么做错了/不理解?


您添加参考单个阵列多次另一个阵列。看看这个简单的例子:

  VAR一个= [];
变种B = [A,一个];一个[0] = 42;
的console.log(B);
// [42],[42]]

你可以看到,我设置 A B 数组的第一和第二个元素。没有理由为什么这个操作应该在这个过程中创造的 A 两个副本。这两种元素引用相同的数组,可以方便的与测试

  B [0] === B〔1] //真

两个不同的阵列将永远彼此相等( [] === [] 收益


解决方案: 第二循环中创建数组的副本:

 为(VAR I = 0; I<地图宽度;我++){
    board.push(columns.slice(0));
}

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?

解决方案

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

这篇关于在2维数组JS选择对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆