乐趣区

关于javascript:JS中forEach赋值值得注意的地方

let data = [{a: 1},
  {a:2}
]
data.forEach(v => {v.title = "hello"})

console.log(data) // [{a: 1, title: "hello"}, {a:2, title: "hello"} ] 胜利赋值 
let data = [{a: 1},
  {a:2}
]
data.forEach(v => {v = {a:1, title: "你好"}
})

console.log(data) // [{a: 1}, {a:2} ] 赋值失败 

正确的写法:

let data = [{a: 1},
  {a:2}
]
data.forEach((v, i) => {data[i] = {a:1, title: "你好"}
})
console.log(data) // [{a: 1, title: "你好"}, {a:1,  title: "你好"} ] 赋值胜利 
退出移动版