在JavaScript中定义3D数组

时间:2016-06-27 11:31:02

标签: javascript arrays multidimensional-array

我尝试在Google Sheet上定义一个3D数组,但即使我使用的是.slice()方法,它也会继续通过引用传递数组。

 var temp = [];
 for (var a = 0; a<archetypesAll.length; a++) {temp[a] = [0, a].slice();};
 var archRank = []; 
 for (var a = 0; a<21; a++) {archRank[a]= temp.slice();};
 archRank[2][1][0] = 'Test';

我想编辑矩阵的单个元素,但上面的代码只是用完全相同的值填充每一行('Test'):

3DMatrix[x][1][0] = 'Test'

2 个答案:

答案 0 :(得分:0)

var array = ["Test", "Test"];    
var array3d = [[array.slice(0)],[[array.slice(0)]]];
array3d[0][0][0] = "Changed";
console.log(JSON.stringify(array3d)); //[[["Changed","Test"]],[[["Test","Test"]]]]

尝试使用此而不是切片来获取新数组而不是引用:

var temp = [];
for (var a = 0; a < archetypesAll.length; a++) {
   temp[a] = JSON.parse(JSON.stringify([0, a]));
}
var archRank = []; 
for (var a = 0; a < 21; a++) {
   archRank[a]= temp.slice();
}
archRank[2][1][0] = 'Test';

答案 1 :(得分:0)

您不能通过在顶层调用slice来复制多维数组,因为这不会对整个数据进行深层复制。您必须编写自己的deepCopy methid,如下所示:

&#13;
&#13;
function allocate(mainDim, ...dims) {
  const result = new Array(mainDim);
  for (let i = 0; i < result.length; i++) {
    result[i] = dims.length > 0 ? allocate(...dims) : 0;
  }
  return result;
}

function deepCopy(matrix, dims) {
  return dims > 1 ? matrix.map(row => deepCopy(row, dims - 1)) : matrix.slice();
}

function test() {
  const mx1 = allocate(3,2,2);
  mx1[2][1][0] = "Test";
  console.log(JSON.stringify(mx1));
  const mx2 = deepCopy(mx1, 3);
  mx2[2][1][0] = "Copied";
  console.log(JSON.stringify(mx1));
  console.log(JSON.stringify(mx2));
}
test();
&#13;
&#13;
&#13;