let arr = []
for (let i = 0; i < 10; i++) {arr[i] = [{id: 'a'}, {id: 'b'}, {id: 'c'}, {id: 'd'}, {id: 'e'}]}
for (let i in arr) {
for (let j in arr[i]) {
arr[i][j].name = i
}
}
console.log(arr)
错误的结果
let arr = []
let arr1 = [{id: 'a'}, {id: 'b'}, {id: 'c'}, {id: 'd'}, {id: 'e'}]
for (let i = 0; i < 10; i++) {arr[i] = arr1}
for (let i in arr) {
for (let j in arr[i]) {
arr[i][j].name = i
}
}
console.log(arr)
你这个应该是js引用导致的问题
下面两段代码中,第一段为正常,第二段为错误
正常的结果
let arr = [] for (let i = 0; i < 10; i++) {arr[i] = [{id: 'a'}, {id: 'b'}, {id: 'c'}, {id: 'd'}, {id: 'e'}]} for (let i in arr) { for (let j in arr[i]) { arr[i][j].name = i } } console.log(arr)
错误的结果
let arr = [] let arr1 = [{id: 'a'}, {id: 'b'}, {id: 'c'}, {id: 'd'}, {id: 'e'}] for (let i = 0; i < 10; i++) {arr[i] = arr1} for (let i in arr) { for (let j in arr[i]) { arr[i][j].name = i } } console.log(arr)
原因是由于数组都引用的同一个对象,后面的修改导致前面的也被改动了
这个问题是属于js引用的问题
解决方式
写个代码片段