首页 > 解决方案 > Javascript:推入一个空的 3d 数组

问题描述

我创建了一个空的 3x3x1 3D 数组

[
  [[],[],[]],
  [[],[],[]],
  [[],[],[]]
]

现在,位置的元素arr[1][1][],所以,如果我执行arr[1][1].push(1)它应该插入1位置arr[1][1]

在 JS 中创建一个空的 3x3x1 数组有 2 种方法,这里是代码,

var arr1 = [...new Array(3)].map(e => [...new Array(3)].fill([]));
var arr2 = [[[],[],[]],[[],[],[]],[[],[],[]]];
arr1[1][1].push(1);
arr2[1][1].push(1);
console.log(arr1)
console.log(arr2)

IE。通过快捷方式和另一个手动,两者arr1arr2应该是相同的,所以应该是输出,但是输出如下,

[[[], [], []], [[1], [1], [1]], [[], [], []]]

[[[], [], []], [[], [1], []], [[], [], []]]

为什么第一个数组会给出这样的输出?两者不一样吗?

我希望输出是第二种形式,如果这是创建空 3x3x1 数组的错误方法,请建议一种方法,以便它提供预期的输出。

标签: javascriptarrayspush

解决方案


再使用一张嵌套地图。我认为该调用将在每个第二维中使用相同fill的数组填充第一个,而不是唯一的,这意味着第二维都引用相同的数组。map

来自的文档fill甚至注意到这value将是完全相同的:

填充数组的值。(注意数组中的所有元素都是这个精确值。)

另外(数组是一个对象):

如果第一个参数是一个对象,则数组中的每个槽都将引用该对象。

const arr1 = [...new Array(3)].map(e => [...new Array(3)].fill([]));
const arr2 = [[[],[],[]],[[],[],[]],[[],[],[]]];
const arr3 = [...new Array(3)].map(() => [...new Array(3)].map(() => []));

arr1[1][1].push(1);
arr2[1][1].push(1);
arr3[1][1].push(1);

console.log(JSON.stringify(arr1)); // [[[],[],[]],[[1],[1],[1]],[[],[],[]]]
console.log(JSON.stringify(arr2)); // [[[],[],[]],[[],[1],[]],[[],[],[]]]
console.log(JSON.stringify(arr3)); // [[[],[],[]],[[],[1],[]],[[],[],[]]]

换句话说:

const expandedArr1 = [...new Array(3)].map(() => {
  /*
   * From MDN fill documentation:
   * Value to fill the array with. (Note all elements in the array will be this exact value.)
   */
  return [...new Array(3)].fill([]); // Every element will get this exact value (reference)
});

// They are the same reference:
console.log(expandedArr1[1][1] === expandedArr1[1][2]);


推荐阅读