迹忆客 专注技术分享

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

JavaScript 中填充数组

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

在 JavaScript 中,Array.prototype.fill() 连续工作以填充某个范围数组。但是,根据浏览器的不同,许多元素的操作可能会变慢。

或多或少,大多数填充数组的方式都面临着大量元素的这种缓慢的步伐。但有些方法在快速比较运算的情况下效果更好。

在这里,我们将看到方法 fill()map()from()apply() 和基本 loop 语句填充数组的应用。让我们跳到代码行。

此方法需要一行代码来初始化数组元素。fill() 方法的默认函数完成了填充数组的工作。

代码片段:

var a = new Array(5).fill(1);
console.log(a);

输出:

使用 Array.prototype.fill() 填充数组

在这里,我们将使用扩展运算符来扩展数组的元素,然后在每个元素上应用 map() 以用一个值填充它们。代码解释得更好。

代码片段:

var a = [...new Array(5)].map(x=>2);
console.log(a);

输出:

使用 Array.prototype.map() 填充数组

在这种情况下,我们将使用 Array.from() 方法,该方法将接受一个定义其范围的数组实例,并且还将有一个函数集将初始化 lambda 函数范围中描述的元素值。让我们检查一下代码块。

代码片段:

var a = Array.from(Array(5),() => 3);
console.log(a);

输出:

使用 Array.from() 方法填充数组

我们将使用 apply() 方法将数组的所有元素保持在一定范围内。稍后,我们将使用 map() 函数为每个元素赋值。

var a = Array.apply(null, Array(5)).map(Number.prototype.valueOf,4);
console.log(a);

输出:

使用 apply() 方法填充一个数组

在这里,我们将使用一个基本循环来遍历数组的元素直到指定范围,然后初始化这些值。

代码片段:

var a = new Array(5);
for(var i=0;i<5;i++){
  a[i]=5;
}
console.log(a);

输出:

使用循环语句填充数组

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

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便