迹忆客 专注技术分享

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

在 JavaScript 中创建特定长度的数组

作者:迹忆客 最近更新:2023/03/10 浏览次数:

在 JavaScript 中,你可能需要创建或声明一个特定长度的数组,并在数组中插入所需的值。它可以使用不同的方式来实现。

下面是一些在 JavaScript 中创建特定长度数组的最常用方法。现在只在你认为需要的情况下使用它,因为大多数情况下,不需要创建或声明特定长度的数组;你可以动态创建一个数组并使用它。

创建特定长度的空数组的第一种方法是使用 Array() 构造函数并将整数作为参数传递给它。由于我们正在调用构造函数,因此我们将使用 new 关键字。

var arr = new Array(5);
console.log(arr)

输出:

[undefined, undefined, undefined, undefined, undefined]

如果你使用 JSlint,不推荐这种创建特定长度数组的方式,因为它可能会导致问题。由于这种方式是模棱两可的,它不仅创建特定长度的数组,还可以用于执行其他操作,例如创建包含值的数组,如下所示。

var arr_2 = new Array('5');
console.log(arr_2)

输出:

[ "5" ]

Array 构造函数提供了一个名为 apply() 的方法。使用这个 apply() 方法,你可以以数组的形式为方法提供参数。apply() 方法有两个参数,第一个是对 this 参数的引用,第二个是数组。

var myArr = Array.apply(null, Array(5));
console.log(myArr);

输出:

[undefined, undefined, undefined, undefined, undefined]

要创建一个特定长度的空数组,假设为 5,我们将传递 null 作为第一个参数,第二个参数是数组 Array(5)。这将创建一个长度为 5 的数组,并使用 undefined 值初始化每个元素。

或者,你也可以执行以下操作。在这里,你可以传递一个数组对象作为第二个参数,然后在其中定义要创建的数组的长度,在本例中为 5

var arr = Array.apply( null, { length: 5 } );
console.log(arr);
console.log(arr.length);

输出:

[undefined, undefined, undefined, undefined, undefined]
5

另一种创建特定长度数组的方法是使用 JavaScript 中的 map() 方法。在这里,Array(5) 构造函数将创建一个长度为 5 的空数组。这与我们之前看到的类似。然后使用扩展运算符 ...,我们将扩展数组的每个元素并将其括在一个像这样的方括号内 [...Array(5)]。它将创建一个长度为 5 的数组,其中每个元素的值都是 undefine。然后为了初始化这个数组,我们将使用 map() 方法。

[...Array(5)].map(x => 0);

输出:

[0, 0, 0, 0, 0]

使用 map() 方法,我们将获取 x 变量中的每个元素,然后向其添加值零。这会将数组的所有元素初始化为零。

fill() 方法的工作方式也与 map() 相同;唯一的问题是 fill() 不接受任何函数作为参数。它直接将一个值作为输入。你可以创建一个特定长度的数组 Array(5),然后用一些整数值填充该数组,如下所示。

Array(5).fill(0);
// [0, 0, 0, 0, 0]

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

用 jQuery 检查复选框是否被选中

发布时间:2024/03/24 浏览次数:102 分类:JavaScript

在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的

扫一扫阅读全部技术教程

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

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便