- 当我们想借助new Array()生成指定数组长度的假数据的时候,我们可以这样写:
const data = new Array(5).map((v, i) => {
return { name: "XXX" + i, price: i, category: Math.random() > 0.5 ? '蔬菜' : '水果' }
})
console.log(data) // (5) [empty × 5]
-
打印后我们发现,数组还是空的。原因在于虽然定义了数组长度为5的数组,但是我们没有往里面添加数据,所以一个长度为5的空数组调用map方法返回的依旧为空数组。
解决办法:使用fill()这个数组方法,由于没有传值,fill()会自动根据数组长度替换数组中所有的值为undefined,这样起码数组有值了!!!
const data = new Array(5).fill()
console.log(data) // (5) [undefined, undefined, undefined, undefined, undefined]
- 以下便是关于new Array().fill的用法了
const data = new Array(5).fill().map((v, i) => {
return { name: "XXX" + i, price: i, category: Math.random() > 0.5 ? '蔬菜' : '水果' }
})
console.log(data)
// (5) [{…}, {…}, {…}, {…}, {…}]
//0: {name: "XXX0", price: 0, category: "蔬菜"}
//1: {name: "XXX1", price: 1, category: "蔬菜"}
//2: {name: "XXX2", price: 2, category: "蔬菜"}
//3: {name: "XXX3", price: 3, category: "水果"}
//4: {name: "XXX4", price: 4, category: "水果"}
//length: 5
//__proto__: Array(0)