JavaScript 中如何初始化对象数组
使用 fill()
方法初始化对象数组,例如 new Array(2).fill({key: 'value'})
。 Array()
构造函数创建指定长度的数组,fill()
方法将数组中的元素设置为提供的值并返回结果。
const arr1 = new Array(2).fill({key: 'value'});
// 👇️ [{key: 'value'}, {key: 'value'}]
console.log(arr1);
我们传递给 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);
我们使用 Array()
构造函数创建了一个包含 2 个空元素的数组。
for
循环允许我们遍历数组并将每个空元素分配给一个对象。
选择哪种方法是个人喜好的问题。 我会选择
fill()
方法,因为它是声明性的、易于阅读并且解决了用特定值填充数组的确切问题。
相关文章
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
将 NumPy 数组转换为 Pandas DataFrame
发布时间:2024/04/21 浏览次数:111 分类:Python
-
本教程介绍了如何使用 pandas.DataFrame()方法从 NumPy 数组生成 Pandas DataFrame。
如何将 Pandas Dataframe 转换为 NumPy 数组
发布时间:2024/04/20 浏览次数:176 分类:Python
-
本教程介绍如何将 Pandas Dataframe 转换为 NumPy 数组的方法,例如 to_numpy,value 和 to_records
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。