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

标签 javascript arrays

在下面的 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/

相关文章:

javascript - 使用 jQuery 的简单不区分大小写的表格搜索框

javascript - 将参数传递给 jQuery 选择器

java - 使用数组而不是ArrayList。用户必须写入数组提供的确切数据数。

javascript - 如何编写此正则表达式以获取多行数据并转换为 JSON 数组

javascript - Json - 在数组元素之间插入一个新对象

javascript - IPython内核javascript双向通信的简约示例

javascript - 在 JavaScript 中按插入顺序获取对象键

JavaScript getter 定义为数组而不是函数?

JavaScript Float32Array 检查可转移对象是否已绝育

java - 神经网络和Python