如何使用array.fill创建对象数组? [英] How do I use array.fill for creating an array of objects?

查看:57
本文介绍了如何使用array.fill创建对象数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下JavaScript代码段中,为什么运行此代码段时乏味 concise 中的元素不相等?我从第二个元素中获得了简洁/** ref:2 **/输出.

In the following javascript snippet, why are elements in tedious and concise not equivalent when you run this snippet? I get /**ref:2**/ output for concise from the second element.

const tedious = [
  {},
  {},
  {},
  {},
  {},
  {},
  {},
  {},
  {},
];

const concise = new Array(9).fill({});

console.log(tedious);
console.log(concise);

推荐答案

注意:不确定运行代码段时发生了什么,但是在现实世界中引用事务并没有发生

Note: not sure what is happening in running a snippet, but that ref business does not happen in the real world

根据Xufox注释,

:/** ref:2 **/表示对数组元素2的引用",因为Stack Snippets的控制台功能无法确定您是否已经具有无限嵌套的结构,因此使用了ref注释(和本例中未使用的id注释)

as per Xufox comment: /**ref:2**/ means "reference to element 2 of the array", since the console feature of Stack Snippets can’t know whether you’ve got an infinitely nested structure, so instead the ref comments (and id comments which aren’t used in this case) are used

关于实际的问题

const concise = new Array(9).fill({});

所有9个条目都将引用"同一对象-请参见输出

IS that all 9 entries will "refer" to the same object - see the output

const concise = new Array(9).fill({}); // {} 
concise[0].a='hello world';
console.log(JSON.stringify(concise))

为了更好地说明这一点,让我们将一个非空对象传递给具有随机值的 fill

To better illustrate that, let's pass a non-empty object to fill with a random value

const concise = new Array(9).fill({random:Math.floor(Math.random() * 1000)});
console.log(JSON.stringify(concise))

很明显,该对象只创建了一次

Clearly, that object is created exactly once

尝试

const concise = new Array(9).fill(0).map(() => ({}));

concise[0].a='hello world';
console.log(JSON.stringify(concise))

由于每个元素都会调用一次地图回调,因此每次都会创建一个新对象

as the map callback is called once for each element, a new object is created each time

或者您可以尝试

const concise = Array.from({length:9}, () => ({}));

concise[0].a='hello world';
console.log(JSON.stringify(concise))

Array.from 的第二个参数是对每个元素调用一次的回调,它基本上是相同的 .map

the second argument to Array.from is a callback that is called once for each element, it's basically the same .map

当然,感谢@Slai,以上内容更加简单

And of course, thanks to @Slai, the above is even more simply

const concise = Array.from({length:9}, Object);


将上面的数学随机"代码的输出与


Compare the output of the "math random" code above with

const concise = Array.from({length:9}, () => ({random:Math.floor(Math.random() * 1000)}));
console.log(JSON.stringify(concise))

这篇关于如何使用array.fill创建对象数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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