[英]How does {…object, property: value} work with spread syntax?
When reviewing the ES6 docs, I noted that it is recommended to use the spread syntax over the more verbose Object.assign()
method. 在查看ES6文档时,我注意到建议在更详细的
Object.assign()
方法上使用扩展语法。 But, I am a bit confused as to how this is being accomplished. 但是,我对如何实现这一点感到困惑。
Is object
in this case being broken down to key: value
pairs, after which the property on the right of the comma is either added or overwritten, and finally being reassembled? 在这种情况下,
object
是否被分解为key: value
对,之后是逗号右边的属性是添加还是被覆盖,最后被重新组合?
Is object in this case being broken down to key: value pairs, after which the property on the right of the comma is either added or overwritten, and finally being reassembled?
在这种情况下,对象是否被分解为键:值对,之后是逗号右边的属性是添加还是被覆盖,最后被重新组合?
The key-value pairs of the original object object
are actually being used in combination (merging) with the new object which has an extra property var2
( they are getting combined to newObject
). 原始对象
object
的键值对实际上与新对象组合使用(合并),该对象具有额外的属性var2
(它们将被组合到newObject
)。
You can think of it as object
is becoming a subset of newObject
in the place where the spread syntax in being used, while properties with same key are being overridden. 您可以将其视为
object
正在成为使用扩展语法的地方的newObject
的子集,而具有相同键的属性将被覆盖。
Check the below example: 检查以下示例:
const object = { txt: 'Test' }; const newObject = {...object, var2: 'aa' }; // logs Object {txt: "Test", var2: "aa"} console.log(newObject); const object2 = { txt: 'Test' }; const newObject2 = {...object, txt: 'Test2', var2: 'aa' }; // Object {txt: "Test2", var2: "aa"} console.log(newObject2); // merging all objects to a new object var object3 = {first: 'Hello', second: 'World'}; var newObject3 = {...object, anotherVar: 'stack', ...object2, ...object3}; // Object {txt: "Test", anotherVar: "stack", first: "Hello", second: "World"} console.log(newObject3);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.