简体   繁体   English

扩展运算符等效于对象分配

[英]Spread operator equivalent of Object assign

What would be the equivalent of merging these objects to a spread operator? 将这些对象合并到散布算子中相当于什么? I wanna use spread instead of assign in my redux app. 我想在我的redux应用中使用价差而不是分配。

return Object.assign({}, obj1, obj2)

The equivalent would be: 等效为:

return { ..obj1, ...obj2 };

However this won't work without transpiling (by babel for example), as object rest spread is a stage-3 recommendation, and not supported by current browsers. 但是,如果不进行转译(例如通过babel进行翻译),这将无法工作,因为对象剩余分布是第三阶段的建议,并且当前浏览器不支持。 If you use babel, you'll have to use the Object rest spread transform babel plugin or the babel stage-3 preset . 如果您使用babel,则必须使用Object rest spread transform babel插件或babel stage-3预设

As explained in the docs : 文档中所述:

Note: Typically the spread operators in ES6 goes one level deep while copying an array. 注意:通常,ES6中的散布运算符在复制阵列时会深入一层。 Therefore, they are unsuitable for copying multidimensional arrays. 因此,它们不适合复制多维数组。 It's the same case with Object.assign and Object spread operators. 与Object.assign和Object Spread运算符相同。 Look at the example below for a better understanding. 请看下面的示例,以更好地理解。

This means that the spread is made in anew object, so no need to pass an empty object as is Object.assign . 这意味着扩展是在新对象中进行的,因此不需要像Object.assign一样传递空对象。 Hence you can just do: 因此,您可以执行以下操作:

return {...obj1, ...obj2}

As an additional note, here is how babel transpiles the spread operator: 作为附加说明,这是babel如何转换传播算子:

const a = {...obj1, ...obj2}

becomes: 变为:

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var a = _extends({}, obj1, obj2);

See for yourself 你自己看

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM