3

js生成1到100的数组方法(简单高效)

 1 year ago
source link: https://www.fly63.com/article/detial/12247
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

更新日期: 2022-12-08阅读: 15标签: 数组分享

扫一扫分享

生成1到100的数组的一种方法是使用JavaScript的Array.from()方法。例如,下面的代码将生成1到100的数组:

const numbers = Array.from(Array(100).keys(), n => n + 1);

这段代码使用JavaScript的Array.from()方法来创建一个长度为100的数组,然后对每个数组元素进行映射,使得每个数组元素都是其索引值加1。

还有一种方法是使用JavaScript的map()方法,在现有数组的基础上创建一个新的数组。下面的代码使用这种方法来生成1到100的数组:

const numbers = Array(100).fill(0).map((_, i) => i + 1);

这段代码首先使用Array()方法创建一个长度为100的数组,然后使用fill()方法将数组中的每个元素都设置为0。最后,使用map()方法对每个数组元素进行映射,使得每个数组元素都是其索引值加1。

最后,可以使用JavaScript的for循环来生成1到100的数组。下面是一段使用这种方法的代码:

const numbers = [];
for (let i = 1; i <= 100; i++) {
  numbers.push(i);
}

这段代码创建一个空的数组numbers,然后使用for循环将1到100的数字逐个添加到数组中。

总的来说,JavaScript有多种方法可以用来生成1到100的数组。

链接: https://www.fly63.com/article/detial/12247


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK