推入预填充数组的数组会设置所有元素 [英] Push on array of prefilled arrays sets all elements

查看:60
本文介绍了推入预填充数组的数组会设置所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力处理奇怪的 Array.prototype.fill 行为:

I'm struggling with a weird Array.prototype.fill behaviour:

const arr = new Array(5)
   .fill([]);
arr[0].push('element pushed to 0 only');
console.log(arr[1]); // ['element pushed to 0 only']

数组中的所有项目都用此字符串填充.我假设所有 [] 数组都指向同一个数组,但是我不明白为什么,有人可以解释吗?

All of the items inside the array are filled with this string. I assume all of the [] array-s are pointing to the same array, but I don't see why, could anyone explain?

推荐答案

fill([])中,参数 [] 在调用填充.

const subarray = [];
const arr = new Array(5);
arr.fill(subarray);

const subarray = [];
const arr = new Array(5);
for (var i=0; i<arr.length; i++) arr[i] = subarray;

换句话说,您在所有索引处都具有相同的子数组: arr [1] arr [0] .

In other words you have the same sub array at all indices: arr[1] is arr[0].

如果您想拥有不同的子数组,您可以这样做

If you want to have different subarrays, you coul do

const arr = Array.from({length:5}, ()=>[]);

这篇关于推入预填充数组的数组会设置所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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