由Array.prototype.fill()填充的数组的奇怪行为 [英] Strange behavior of an array filled by Array.prototype.fill()

查看:49
本文介绍了由Array.prototype.fill()填充的数组的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我面对一些数组无法理解的东西.确实,我创建了一个用空的subArray填充的数组以获得2D矩阵. 但是,当我操作数组时,它的行为不符合我的预期.

I face something I don't understand with an array. Indeed, I created an array I have filled with empty subArrays to obtain a 2D Matrix. But when I manipulate the array it doesn't behave as I expected.

var arr = new Array(5);
arr.fill([]);
arr[2].push("third rank item");
console.log(arr);

//[ [ 'third rank item' ],
//  [ 'third rank item' ],
//  [ 'third rank item' ],
//  [ 'third rank item' ],
//  [ 'third rank item' ] ]

在此问题上的所有亮光都将受到欢迎

Every lights on this matter will be welcomed

推荐答案

这与数组(和对象通常是引用)而不是值是同样的老问题.

This is the same old problem with arrays (and objects in general) being references rather than values.

具体来说,当您执行arr.fill([])时,您将获取一个空数组,并使用该空数组来填充父数组.

Specifically, when you do arr.fill([]), you are taking that one single empty array and using that to fill the parent one.

这就像在说:

var arr = new Array(5);
arr[0] = arr[1] = arr[2] = arr[3] = arr[4] = [];

它们都引用相同的数组!因此,当您继续修改其中之一时,看起来它们都已修改(但实际上还是一样)

They all refer to the same array! So when you then go on to modify one of them, it looks like they're all modified (but really it's still the same one)

不幸的是,没有简单的方法可以为每个数组分配一个空数组.您可以执行以下操作:

Unfortunately there's no simple way to assign an empty array to each one. You could do something like:

Array.apply(null, Array(5)).map(function() {return [];});

基本上,创建一个长度为5的(初始化)空数组,并将每个(空)值映射到新的[].

Essentially, create an (initialised) empty array of length 5 and map each (empty) value to a new [].

似乎我陷入了过去.根据@torazaburo的评论,您可以使用Array.from代替Array.apply(null, Array(5)).map,就像这样:

Seems like I'm stuck in old times. As per @torazaburo's comment, you can use Array.from instead of Array.apply(null, Array(5)).map, like so:

Array.from( new Array(5), function() { return []; } );

这篇关于由Array.prototype.fill()填充的数组的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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