gpt4 book ai didi

javascript - 如何使用 array.fill 创建对象数组?

转载 作者:行者123 更新时间:2023-12-01 01:58:27 25 4
gpt4 key购买 nike

在下面的 JavaScript 代码段中,为什么当您运行此代码段时,tediousconcise 中的元素不相等?我从第二个元素获得 /**ref:2**/ 输出,表示 concise

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

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

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

最佳答案

注意:不确定运行代码片段时发生了什么,但引用业务在现实世界中不会发生

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 个条目都将“引用”同一个对象 - 请参阅输出

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

为了更好地说明这一点,我们将一个非空对象传递给 fill 并使用随机值

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

显然,该对象只创建一次

尝试

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

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

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

或者你可以尝试

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

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

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

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

const concise = Array.from({length:9}, Object);
<小时/>

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

进行比较

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

关于javascript - 如何使用 array.fill 创建对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50807131/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com