迹忆客 专注技术分享

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

在 JavaScript 中初始化布尔值数组

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

要初始化布尔值数组,请使用 Array() 构造函数创建特定长度的数组,并调用数组上的 fill() 方法以用布尔值填充它,例如 new Array(3).fill(false) 创建一个包含 3 个元素且值为 false 的数组。

const arr1 = new Array(3).fill(false);

// 👇️ [false, false, false]
console.log(arr1);

JavaScript 中初始化布尔值数组

我们传递给 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);

JavaScript 中使用 for 循环初始化布尔值数组

我们使用 Array() 构造函数创建了一个包含 3 个空元素的数组,就像上一个示例一样。

下一步是使用 for 循环遍历数组,为每个空元素分配一个布尔值。

Array.fill() 方法是我的首选方法。 该方法比 for 循环更简洁和声明,并解决了用提供的值填充数组的特定问题。

转载请发邮件至 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

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便