1
在代碼審查,有人指出,我可以用傳播經營者和不斷更新的對象:爲什麼const通過spread運算符更新屬性?
const props = {
hairColor: 'brown',
};
const hairColor = 'red';
const newProps = { ...props, hairColor};
console.log(newProps); // -> hairColor now equals 'red'
的問題是,如何工作的呢?
我理解實際上如何傳遞對象的工作原理:
const newProps = { ...props, { hairColor: 'red' }};
但它是如何知道更新hairColor
與價值「紅」?一個快速測試顯示它使用變量名稱,但是如何?
const props = {
hairColor: 'brown',
};
const colorOfHair = 'red';
const newProps = { ...props, colorOfHair};
// -> hairColor still equals 'brown'
// with new property 'colorOfHair'
console.log(newProps);
這就是所謂的[速記屬性名稱(HTTPS ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#New_notations_in_ECMAScript_2015)。 –