4
JS中forEach赋值值得注意的地方
source link: https://segmentfault.com/a/1190000040450607
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
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: "你好"} ] 赋值成功
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK