需求:
循環創建符合要求的對象后,將其保存進數組內
代碼:
randomImgYield(num1, num2) {
let NumImgRandom = []
for (let i1 = 0; i1 < num1; i1++) {
/** * 循環往數組里添加數組或對象時,需要在循環里創建需要添加的數據變量,保證在局部作用域內有效 * 若在循環外let創建,那對象的內存指針都會指向為最后一個的內存指針 * 則添加的一直為最后的那個對象 */
let ImgArray = [] for (let i2 = 0; i2 < num2; i2++) { let img = {} img.a = this.imgSonDate_set() img.b = this.imgSonSerial_set() img.c = this.imgSonLotNumber_set() ImgArray.push(img) }
NumImgRandom.push(ImgArray)
// this.letter必須再一張圖-6個內容塊生成完后清空,否則imgSonSerial_set()會陷入死循環
this.letter = []
}
},
重點:
用於保存的數組需要在循環外創建,而生成的對象需要每次在循環內創建;而不能是在循環外創建好后在循環內進行賦值
因為若在循環外let創建,那對象的內存指針都會指向為最后一個的內存指針,則添加的一直為最后的那個對象
列如:(錯誤示范)
let ImgArray = []
let img = {} for (let i2 = 0; i2 < 3; i2++) { img.id = i ImgArray.push(img) }
最后 ImgArray 結果實際為:[ { id:2 },{ id:2 },{ id:2 } ]