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

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

问题描述

只是一个小问题。

我玩弄了一下,并试图实例lenght x的新阵列,哪里哪里初始化为一个值y数组中的所有元素

I was toying a bit and was trying to instantiate a new array of lenght x, where all elements of that array where 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 is 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?

在此先感谢!

推荐答案

您可以先填写与任何值(例如未定义<阵列/ code>),然后你就可以使用地图

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