一般我们生成一个有规律的数组会使用循环插入的方法,比如使用时间选择插件时,我们可能需要将小时数存放在数组中:
let hours = [];
for (let i = 0; i < 24; i++) {
hours.push(i + '时');
}
如果使用 Array.from 我们可以简写为:
let hours = Array.from({ length: 24 }, (value, index) => index + '时');
这篇博客介绍了如何使用JavaScript优雅地生成有规律的数组,比较了传统for循环与Array.from方法的用法。通过实例展示了如何利用Array.from简洁地创建包含24小时的数组,提高了代码的可读性和简洁性。
一般我们生成一个有规律的数组会使用循环插入的方法,比如使用时间选择插件时,我们可能需要将小时数存放在数组中:
let hours = [];
for (let i = 0; i < 24; i++) {
hours.push(i + '时');
}
如果使用 Array.from 我们可以简写为:
let hours = Array.from({ length: 24 }, (value, index) => index + '时');

被折叠的 条评论
为什么被折叠?