批量快捷创建新数组的几种方式
1. for循环, push(比较简单, 就不上代码了)
2.创建空数组,填充null,然后map:
function createData() {
return new Array(1000)
.fill(null)
.map((v,i)=>({name: `name${i+1}`}))
}
console.log(createData())
3.Array.from+map
function createData() {
return Array.from({length: 1000})
.map((v,i)=>({name: `name${i+1}`}))
}
console.log(createData())
4.Array.from的第二个fn参数
function createData() {
return Array.from({length: 1000}, (v,i)=>({name: `name${i+1}`}))
}
console.log(createData())
5. Array.of(...数组或类数组)
eg: Array.of(1, 2, 4, 7) => [1, 2, 4, 7]; 想变成新数组, 再链式调用map就行了
6. 手写数据生成器:
function createValues(creator, length = 1) {return Array.from({ length }, creator)
}
1) 随机数据生成器:
const createRandomValues = (len) => createValues(Math.random, len)
// createRandomValues(10) // 10个随机数字组成的数组
2) 序列生成器
const createRange = (start, stop, step) => {const arr = createValues((_, i) => start + (i * step), Math.floor((stop - start) / step) + 1)return arr
}
但是上面在(stop - start) / step有余数时, stop没有打印出来, 因为不符合step的规律, 比如start为1,stop为99, step为3, 但是最后一个元素为97的时候就结束了:
// [1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31, 34, 37, 40, 43, 46, 49, 52, 55, 58, 61, 64, 67, 70, 73, 76, 79, 82, 85, 88, 91, 94, 97]
createRange(1, 99, 3);
而有的时候, 或者说大多数时候希望执行到最后一个元素, 可以判断arr[len -1]<stop的时候把stop的值push进去
const createRange = (start, stop, step) => {const arr = createValues((_, i) => start + (i * step), Math.floor((stop - start) / step) + 1)const len = arr.length// 如果最后一项小于stop的值, push一下stop的值if(arr[len -1]<stop) {arr.push(stop)}return arr
}
3) 生成对象数组
// 数据生成器:
function createUser(v, index) {return {name: `user-${index}`,// 0-100随机数字, >> 0 取整age: Math.random() * 100 >> 0}
}
// 生成10条对象数据的数组
const users = createValues(createUser, 10)