JavaScript 中填充数组
在 JavaScript 中,Array.prototype.fill()
连续工作以填充某个范围数组。但是,根据浏览器的不同,许多元素的操作可能会变慢。
或多或少,大多数填充数组的方式都面临着大量元素的这种缓慢的步伐。但有些方法在快速比较运算的情况下效果更好。
在这里,我们将看到方法 fill()
、map()
、from()
、apply()
和基本 loop
语句填充数组的应用。让我们跳到代码行。
此方法需要一行代码来初始化数组元素。fill()
方法的默认函数完成了填充数组的工作。
代码片段:
var a = new Array(5).fill(1);
console.log(a);
输出:
在这里,我们将使用扩展运算符来扩展数组的元素,然后在每个元素上应用 map()
以用一个值填充它们。代码解释得更好。
代码片段:
var a = [...new Array(5)].map(x=>2);
console.log(a);
输出:
在这种情况下,我们将使用 Array.from()
方法,该方法将接受一个定义其范围的数组实例,并且还将有一个函数集将初始化 lambda 函数范围中描述的元素值。让我们检查一下代码块。
代码片段:
var a = Array.from(Array(5),() => 3);
console.log(a);
输出:
我们将使用 apply()
方法将数组的所有元素保持在一定范围内。稍后,我们将使用 map()
函数为每个元素赋值。
var a = Array.apply(null, Array(5)).map(Number.prototype.valueOf,4);
console.log(a);
输出:
在这里,我们将使用一个基本循环来遍历数组的元素直到指定范围,然后初始化这些值。
代码片段:
var a = new Array(5);
for(var i=0;i<5;i++){
a[i]=5;
}
console.log(a);
输出:
相关文章
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 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。