javascript - 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。通过快捷方式和另一个手动,两者arr1
和arr2
应该是相同的,所以应该是输出,但是输出如下,
[[[], [], []], [[1], [1], [1]], [[], [], []]]
[[[], [], []], [[], [1], []], [[], [], []]]
为什么第一个数组会给出这样的输出?两者不一样吗?
我希望输出是第二种形式,如果这是创建空 3x3x1 数组的错误方法,请建议一种方法,以便它提供预期的输出。
解决方案
再使用一张嵌套地图。我认为该调用将在每个第二维中使用相同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]);
推荐阅读
- c# - 在 UWP 的 DriveInfo 中访问 AvailableFreeSpace/TotalSize 时出错
- android - 使用代理进行 firebase 实时数据库连接
- git - 从现有存储库创建新存储库
- javascript - jQuery 在点击功能时动态更改图标
- kubernetes - 无法访问部署在 kubernetes 集群上的应用程序
- ffmpeg - FFmpeg 混合模式不适用于“乘法”选项
- java - 使用 h2o rest api 获取模型信息时总是出错
- javafx - javafx中的高CPU使用率
- python - 使用循环 For 和 If 在文件中查找字符串
- json - 使用 jq 将 bash 变量插入 json