spread运算符
Last week I wrote 6 Great Uses of the Spread Operator, a post detailing how awesome the spread operator (...
) is for working with arrays and other iterable objects. As always my readers chimed in with a few other great uses and which you should check out in the comments. And of course as soon as I publish the post I find another great use of the spread operator while I tinker with Babel and React: merging multiple objects' properties into one object!
上周,我写了《 Spread运算符的6大用法》 ,详细介绍了Spread运算符( ...
)对于处理数组和其他可迭代对象的效果。 像往常一样,我的读者还有其他一些很棒的用途,您应该在评论中查看。 当然,当我发布该帖子时,我在修补Babel和React时发现了散布运算符的另一种出色用法:将多个对象的属性合并到一个对象中!
JavaScript (The JavaScript)
Wrap any objects you'd like merged into one with braces ({}
):
用大括号( {}
)将要合并的所有对象包装起来:
const person = { name: 'David Walsh', gender: 'Male' };
const tools = { computer: 'Mac', editor: 'Atom' };
const summary = {...person, ...tools};
/*
Object {
"computer": "Mac",
"editor": "Atom",
"gender": "Male",
"name": "David Walsh",
}
*/
A new object is created containing all properties and values from the objects provided with the rest operator. Also note that you can provide any number of objects to merge:
将创建一个新对象,其中包含rest运算符提供的对象中的所有属性和值。 还请注意,您可以提供任意数量的对象进行合并:
const person = { name: 'David Walsh', gender: 'Male' };
const tools = { computer: 'Mac', editor: 'Atom' };
const attributes = { handsomeness: 'Extreme', hair: 'Brown', eyes: 'Blue' };
const summary = {...person, ...tools, ...attributes};
/*
Object {
"computer": "Mac",
"editor": "Atom",
"eyes": "Blue",
"gender": "Male",
"hair": "Brown",
"handsomeness": "Extreme",
"name": "David Walsh",
}
*/
In the case of a key collision, the right-most (last) object's value wins out:
如果发生键冲突,则最右边(最后一个)对象的值将获胜:
const person1 = { name: 'David Walsh', age: 33 };
const person2 = { name: 'David Walsh Jr.', role: 'kid' };
const merged = {...person1, ...person2}
/*
Object {
"name": "David Walsh Jr.",
"age": 33,
"role": "kid",
}
*/
I love how easy merging objects is using the spread operator. You can use Object.assign
to accomplish the same feat but the spread operator makes things a bit shorter if you don't mind a slightly less descriptive syntax!
我喜欢使用散布运算符轻松合并对象。 您可以使用Object.assign
来完成相同的功能,但是如果您不介意描述性语法稍差一点,那么蔓延运算符会使事情变得更短!
Note: This syntax is not yet support by all browsers but you can use Babel with the transform-object-rest-spread
plugin to enable object merging with the spread operator.
注意:并非所有浏览器都支持此语法,但是您可以将Babel与transform-object-rest-spread
插件一起使用,以启用对象与spread运算符的合并。
spread运算符