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

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

问题描述

我用数组遇到了一些我不明白的事情.事实上,我创建了一个用空子数组填充的数组来获得一个二维矩阵.但是当我操作数组时,它的行为不像我预期的那样.

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天全站免登陆