为什么函数从调用后者后将2Darray参数重新分配为副作用

时间:2018-11-06 19:19:24

标签: javascript

当我单独运行第三行并记录test2darr时,它将返回一个3D3矩阵中填充有6的2D数组
但是,当我运行第四行并再次登录test2darr时,它将返回:
 [4,5,4]
  [5,6,5]
[4,5,4]
 (以及用于第二测试)
尽管它应该为test2darr返回相同的6数组,然后将2d数组分配给secondtest

const n = 3;
const filler = new Array(n * n);

const test2darr = fill2DarrFromArr(filler.fill(6));

const secondtest = pileReduce(test2darr);

这是我的fill2DarrFromArr和PileReduce的代码:

function pileReduce(_cells) { 

    _cells = fillEmpty(_cells);

    for (let j = 0; j < _cells.length; j++) { //The Algorithm itself is not important 
        for (let i = 0; i < _cells.length; i++) { // But there might be some assignment problem that I missed
            if (_cells[j][i] >= 4) {
                _cells[j][i] = _cells[j][i] - 4;

                if (j !== _cells.length - 1) _cells[j + 1][i]++;
                if (j !== 0) _cells[j - 1][i]++;
                if (i !== _cells.length - 1) _cells[j][i + 1]++;
                if (i !== 0) _cells[j][i - 1]++;
            }
        }
    }
    return _cells;
}

function fill2DarrFromArr(_arr) { 
     let sideLength = Math.sqrt(_arr.length);
     let out = create2DArr(sideLength, sideLength);
    for (let j = 0; j < sideLength; j++) {
        for (let i = 0; i < sideLength; i++) {
            out[j][i] = _arr[j * sideLength + i];
        }
    }
    return out;
}

function create2DArr(_n, _m) {
    let _arr = new Array(_n);

    for (let j = 0; j < _m; j++) {
        _arr[j] = new Array(_m);
    }
    return _arr;
}

function fillEmpty(_arr) {
    for (let j = 0; j < _arr.length; j++) {
        for (let i = 0; i < _arr.length; i++) {
            if (!_arr[j][i]) _arr[j][i] = 0;
        }
    }
    return _arr;
}

1 个答案:

答案 0 :(得分:0)

将数组传递给函数不会创建该数组的副本。您的函数正在修改传递的数组的内容,因此有副作用。