批量快捷创建新数组的几种方式

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就行了

你可能感兴趣的:(JavaScript面试问题,javascript,前端)