为什么点差运算符会将“Stratford”的值替换为“HB woodlawn”?这是如何工作的?
const editName = (oldName, name, arr) =>
arr.map(item => {
if (item.name === oldName) {
return {
...item,
name
}
} else {
return item
}
})
let schools = [
{ name: "Yorktown"},
{ name: "Stratford" },
{ name: "Washington & Lee"},
{ name: "Wakefield"}
]
let updatedSchools = editName("Stratford", "HB Woodlawn", schools)
console.log( updatedSchools[1] ) // { name: "HB Woodlawn" }
console.log( schools[1] ) // { name: "Stratford" },
答案 0 :(得分:9)
归结为:
const oldObject = { name: 'Stratford' };
const newObject = { ...oldObject, name: 'HB Woodlawn' };
您可以将其视为将oldObject
的属性扩展为新的对象文字:
const newObject = { name: 'Stratford', name: 'HB Woodlawn' };
文字中具有相同键的属性获取最后一个的值。