在代码审查期间,有人指出我可以使用扩展运算符和常量来更新对象:
const props = {
hairColor: 'brown',
};
const hairColor = 'red';
const newProps = { ...props, hairColor};
console.log(newProps); // -> hairColor now equals 'red'
问题是,这是如何运作的?
我了解传递对象的实际工作原理:
const newProps = { ...props, { hairColor: 'red' }};
但是它怎么知道用值“red”更新 hairColor
呢?快速测试显示它正在使用变量名,但如何使用?
const props = {
hairColor: 'brown',
};
const colorOfHair = 'red';
const newProps = { ...props, colorOfHair};
// -> hairColor still equals 'brown'
// with new property 'colorOfHair'
console.log(newProps);
最佳答案
这是 ES6 shorthand property names .当你在对象中写name
时,它是name: name
的快捷方式。所以
const newProps = { ...props, hairColor};
是
的缩写const newProps = { ...props, hairColor: hairColor};
这与展开运算符无关,如果你这样写,也会发生同样的事情:
const newProps = { prop1: 1, prop2: 2, hairColor };
关于javascript - 为什么 const 通过扩展运算符更新属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47360721/