Array.prototype.fill() 与对象传递引用而不是新实例 [英] Array.prototype.fill() with object passes reference and not new instance

查看:25
本文介绍了Array.prototype.fill() 与对象传递引用而不是新实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点玩弄并试图实例化一个长度为 x 的新数组,其中该数组的所有元素都被初始化为一个值 y:

I was toying a bit and was trying to instantiate a new array of length x, where all elements of that array were initialized to a value y:

var arr = new Array(x).fill(y);

如果y 的值不是一个对象,这很有效.这意味着如果 y 是一个对象,则以下为真:

This works well if the value of y is anything other than an object. Meaning that if y is an object, the following is true:

var arr = new Array(2).fill({});
arr[0] === arr[1]; //is true;
arr[0].test = 'string';
arr[1].test === 'string'; //is also true;

有什么方法可以说明在使用填充函数时应该为每个元素创建一个新对象吗?还是我应该将其转换为循环?

Is there any way to state that a new object should be created for each element while using the fill-function? Or should I just convert it to a loop?

推荐答案

你可以先用任意值(例如 undefined)fill 数组,然后你就会能够使用map:

You can first fill the array with any value (e.g. undefined), and then you will be able to use map:

var arr = new Array(2).fill().map(u => ({}));

var arr = new Array(2).fill().map(Object);

这篇关于Array.prototype.fill() 与对象传递引用而不是新实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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