在 JavaScript 中初始化布尔值数组
要初始化布尔值数组,请使用 Array()
构造函数创建特定长度的数组,并调用数组上的 fill()
方法以用布尔值填充它,例如 new Array(3).fill(false)
创建一个包含 3 个元素且值为 false 的数组。
const arr1 = new Array(3).fill(false);
// 👇️ [false, false, false]
console.log(arr1);
我们传递给 Array()
构造函数的唯一参数是数组应包含的空元素的数量。
console.log(new Array(3)); // 👉️ [ , , ]
Array()
构造函数基本上创建一个新数组并将其长度属性设置为提供的整数。
const arr = [];
arr.length = 3;
console.log(arr); // 👉️ [ , , ]
无论哪种方式,新数组都包含 3 个空元素,我们可以使用 fill()
方法将其设置为布尔值。
我们传递给
fill
方法的唯一参数是我们要分配给数组中每个元素的值。
在具体示例中,3 个数组元素中的每一个都被分配了一个 false 值。
Internet Explorer 不支持
fill()
方法。 如果必须支持浏览器,请改用for
循环。
使用 for 循环初始化一个布尔值数组
要初始化布尔值数组,请使用 Array()
构造函数创建特定长度的数组,并使用 for
循环遍历数组并为每个元素分配一个布尔值。
const arr2 = new Array(3);
for (let i = 0; i < arr2.length; i++) {
arr2[i] = false;
}
// 👇️ [false, false, false]
console.log(arr2);
我们使用 Array()
构造函数创建了一个包含 3 个空元素的数组,就像上一个示例一样。
下一步是使用 for 循环遍历数组,为每个空元素分配一个布尔值。
Array.fill()
方法是我的首选方法。 该方法比 for 循环更简洁和声明,并解决了用提供的值填充数组的特定问题。
相关文章
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 中合并两个数组,以及如何删除任何重复的数组。