我希望JSON.stringify(all) === JSON.stringify(updatedAll2)是false,但它是true。我不明白這樣做的結果。你能解釋一下為什么會這樣嗎?
這是我的代碼:
const all = {
name: "oneny",
schools: [{
name: "Yorktown",
students: 100
},
{
name: "Stratford",
students: 120
},
{
name: "Washington & Lee",
students: 200
},
{
name: "Wakefield",
students: 300
},
],
};
const updatedAll = {
...all,
schools: all.schools.map((e, i) => {
return e.name === "Stratford" ? { ...e,
students: 119
} : e;
}),
}
const updatedAll2 = {
...all,
schools: all.schools.map((e, i) => {
return e.name === "Stratford" ? { ...e,
students: --e.students
} : e;
}),
}
console.log(JSON.stringify(all) === JSON.stringify(updatedAll));
console.log(JSON.stringify(all) === JSON.stringify(updatedAll2));
uj5u.com熱心網友回復:
當你使用 時Array.prototype.map(),如果傳遞給你的回呼的元素是一個物件,那么改變它也會改變原始陣列中的原始物件。要查看實際情況,請在通話all后嘗試列印。.map()你會看到它已經改變了。
const all = {
name: "oneny",
schools: [{
name: "Yorktown",
students: 100
},
{
name: "Stratford",
students: 120
},
{
name: "Washington & Lee",
students: 200
},
{
name: "Wakefield",
students: 300
},
],
};
const updatedAll = {
...all,
schools: all.schools.map((e, i) => {
return e.name === "Stratford" ? { ...e,
students: 119
} : e;
}),
}
const updatedAll2 = {
...all,
schools: all.schools.map((e, i) => {
return e.name === "Stratford" ? { ...e,
students: --e.students
} : e;
}),
}
// Print all, which has been mutated
console.log(all)
console.log(JSON.stringify(all) === JSON.stringify(updatedAll));
console.log(JSON.stringify(all) === JSON.stringify(updatedAll2));
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/520845.html
