在 JavaScript 中用范围填充数组
本文将讨论 Array 类提供的各种方法,我们可以使用这些方法在 JavaScript 中用范围填充数组。
Array.fill()
方法用特定值填充现有数组。
该方法采用三个参数:value
,我们将填充到数组中,以及 start
和 end
,它们描述了我们要在数组中添加数据的位置。start
和 end
是可选参数。
例子:
var arr = [1, 2, 3, 4];
arry.fill(6);
console.log(arr);
输出:
[6, 6, 6, 6]
正如我们所看到的,数组中的所有元素都被成功替换并填充了值 6。如果我们不想用该值替换所有元素,我们可以指定 start
和 end
索引。
在 ES6 版本的 JavaScript 中引入的 Array.from
方法从类似数组的可迭代对象创建数组的浅拷贝实例。
语法:
Array.from(target, mapFunction, thisValue)
其中,
为了填充数组,我们使用 Array.from()
和 Array.keys()
。Array.keys()
方法提取数组的所有键并返回一个迭代器,然后 Array.from()
函数将此迭代器作为参数。
最后,所有索引都被复制为新数组的元素。
例子:
var arr = Array.from(Array(5).keys());
console.log(arr);
输出:
[ 0, 1, 2, 3, 4 ]
除了 Array.from()
函数,我们还可以使用扩展运算符,由三个点 ...
表示。
我们将传递 Array.keys()
,它将返回一个迭代器,并使用扩展运算符 ...
扩展该迭代器中存在的元素,放在 Array.keys()
之前。
之后,我们必须将所有这些括在方括号 []
内以表示一个数组。
扩展运算符将生成与 Array.from
函数相同的输出。
例子:
var arr = [...Array(5).keys()];
console.log(arr);
输出:
[ 0, 1, 2, 3, 4 ]
Array.map()
函数将通过在调用数组的每个元素上运行提供的函数作为参数来创建一个新数组。这可以将任何函数作为参数,例如箭头、回调或内联。
例子:
var elements = 5;
var arr = [...Array(elements)].map((item, index) => index);
console.log(arr);
输出:
[ 0, 1, 2, 3, 4 ]
在上面的例子中,map
函数将箭头函数作为参数来提取 item
和 index
。将在数组的每个元素上调用此箭头函数。
最后,所有数组元素的索引值将被提取并存储在新数组中。
我们讨论过的在 JavaScript 中用范围填充数组的方法被许多开发人员广泛使用。除了这些,我们还可以使用其他方法。
相关文章
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 事件。