迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

JavaScript 中如何初始化对象数组

作者:迹忆客 最近更新:2022/12/16 浏览次数:

使用 fill() 方法初始化对象数组,例如 new Array(2).fill({key: 'value'})Array() 构造函数创建指定长度的数组,fill() 方法将数组中的元素设置为提供的值并返回结果。

const arr1 = new Array(2).fill({key: 'value'});

// 👇️ [{key: 'value'}, {key: 'value'}]
console.log(arr1);

JavaScript 中如何初始化对象数组

我们传递给 Array() 构造函数的参数是数组应包含的空元素的数量。

console.log(new Array(2)); // 👉️ [ , ]

Array() 构造函数在幕后所做的是,它将数组的长度设置为提供的值。

const arr = [];
arr.length = 2;

console.log(arr); // 👉️ [ , ]

我们需要一个包含 N 个空元素的数组,因此我们可以使用 fill() 方法将每个元素的值替换为一个对象。

我们传递给 fill 方法的唯一参数是我们想要填充数组的值。

数组中的 2 个元素中的每一个都被分配了一个对象的值。

或者,我们可以使用简单的 for 循环。


使用 for 循环初始化一个对象数组

要初始化一个对象数组,请使用 Array() 构造函数创建一个填充有 N 个空元素的数组,然后使用 for 循环遍历该数组,将每个元素分配给一个对象。

const arr2 = new Array(2);

for (let i = 0; i < arr2.length; i++) {
  arr2[i] = {key: 'value'};
}

// 👇️ [{key: 'value'}, {key: 'value'}]
console.log(arr2);

使用 for 循环初始化一个对象数组

我们使用 Array() 构造函数创建了一个包含 2 个空元素的数组。

for 循环允许我们遍历数组并将每个空元素分配给一个对象。

选择哪种方法是个人喜好的问题。 我会选择 fill() 方法,因为它是声明性的、易于阅读并且解决了用特定值填充数组的确切问题。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便