记录一个问题:有这样一种需求,需要生成固定长度的对象数组,并对其中不同对象中的相同属性赋予不同的属性值。最终生成效果如下:
needArr = [{manufacturer:'厂家1',type: '类型1'},{manufacturer:'厂家2',type: '类型2'},{manufacturer:'厂家3',type: '类型3'}]
一开始想利用数组的自动生成数组方法:Array(3).fill({manufacturer:' ',type: ' '})
后通过数组的forEach方法来为其中不同对象的相同属性赋予不同的值。
let arr = Array(3).fill({manufacturer:' ',type: ' '})
arr.forEach((item: any, index) => {item.manufacturer = indexitem.type = index + 1
})
console.log(arr)
最终发现打印出来的数组arr如下:
原因:数组的 fill 方法如果接受的值是一个引用数据类型,那么他们会指向同一个地址。
解决:使用map返回出不同的引用的地址
const arr = Array(3).fill({ manufacturer: '', type: '' }).map((item: any, index) => {return {manufacturer: index,type: index + 1,}
})
console.log(arr)
如此打印出的arr为: