多维数组引用实例js

时间:2017-06-29 06:40:58

标签: javascript arrays multidimensional-array reference instance-variables

function obtainArray(n){
    var array = [];
    var row   = [];
    for(var x = 0; x < n; ++x){ row.push(x); }
    for(var x = 0; x < n; ++x){ array.push(row); }
    return array;
    }
            array = obtainArray(8);
            array[1][1] = 'This only must display in array[1][1]';
            console.log(array);

我认为这个问题是因为我喜欢参考行,我希望像实例一样使用。

1 个答案:

答案 0 :(得分:1)

每一行都需要一个空对象。否则,您将保留对所有推送行中单行的引用。

&#13;
&#13;
function obtainArray(n) {
    var array = [],
        row,
        x, y;
    for (x = 0; x < n; ++x) {
        row = [];                  // initialize with empty array
        for (y = 0; y < n; ++y) {
            row.push(y);           // fill array
        }
        array.push(row);           // push array
    }
    return array;
}

array = obtainArray(8);
array[1][1] = 'This only must display in array[1][1]';
console.log(array);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;

使用Array#slice推送行的副本的单循环方法。

  

slice() 方法将数组的一部分的浅表副本返回到从头到尾选择的新数组对象(不包括结尾)。原始数组不会被修改。

&#13;
&#13;
function obtainArray(n) {
    var array = [],
        row = [],
        x;

    for (x = 0; x < n; ++x) {
        row.push(x);             // fill array
    }
    for (x = 0; x < n; ++x) {
        array.push(row.slice()); // push copy
    }
    return array;
}

array = obtainArray(8);
array[1][1] = 'This only must display in array[1][1]';
console.log(array);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;