使用Javascript中的新数组创建2D数组 [英] Creating 2D arrays using new Array in Javascript

查看:71
本文介绍了使用Javascript中的新数组创建2D数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Hackerrank上尝试了一个问题,我需要在其中创建一个数组数组(基本上是2d数组).

I was trying out a question on Hackerrank where I needed to create an array of array (basically 2d arrays).

我要去的班轮是const counter = new Array(4).fill([]) 但是,我意识到它会创建一个2D数组,但是对数组应用任何函数都会使其应用于所有元素.

My go-to one liner would be const counter = new Array(4).fill([]) However, I realized that it would create a 2D array but applying any function to the array would cause it to apply to all the elements.

let count = new Array(4).fill([])
count[0].push("Test")
console.log(JSON.stringify(count))

结果将是所有子数组中具有相同"Test"值的子数组.

The outcome would be all the sub-arrays having the same value of "Test" inside them.

最终的解决方案是:

let count = Array.from(Array(4), () => new Array());
count[0].push("Test")
console.log(JSON.stringify(count))

请问为什么它不能按预期运行?

May I ask the reason why it's not working as expected?

推荐答案

因为.fill()接受参数,并且如果它是一个对象,它将对该对象的引用复制到新数组的每个索引中.由于实际上[]是一个对象,所以您的新数组最终将被对同一数组的引用填充.

Because .fill() takes the argument and, if it's an object, it copies the reference to that object into every index of the new array. Since in fact [] is an object, your new array ends up being filled with references to the same array.

文档中:

如果第一个参数是对象,它将复制其引用,并使用对该对象的引用填充数组.

If the first parameter is an object, it will copy its reference and fill the array with references to that object.

这篇关于使用Javascript中的新数组创建2D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆