如题,Javascript如何生成一个0-60(任意长度)的数组?
最容易理解的方式就是通过for循环往一个空数组添加元素。
var collectArr = [];
for (var i = 0; i <= 60; i++) {
collectArr.push(i);
}
console.log(collectArr);
问题是解决了,但是这样写不简洁明了,写在项目中还略显累赘,有其他方式实现吗?有的。
不考虑浏览器兼容的情况下,直接使用ES6语法是最快速的。
1.Array.from()
const collectArr1 = Array.from(Array(61), (_val, index) => index)
const collectArr2 = Array.from({ length: 61 }, (_val, index) => index)
对一个类似数组或可迭代对象创建一个新的,浅拷贝的数组实例。
参数1:类数组或可迭代的对象
参数2:新数组中的每个元素会执行该回调函数(类似map函数)
2.扩展运算符和keys()
const collectArr3 = [...Array(61)].map((_item,index) => index)
扩展运算符(...):将一个数组转为用逗号分隔的参数序列。
const collectArr4 = [...Array(61).keys()]
Array.prototype.keys():遍历数组的键名(索引),返回一个迭代器对象。
如果要考虑浏览器兼容的情况,使用ES5语法
var collectArr5 = Object.keys(Array.apply(null, {length:61})).map(function (item) { return parseInt(item) });
var collectArr6 = Array.apply(null, Array(61)).map(function (_item, index) { return index } );