假设我有一个选项变量我想设置一个默认值。

这两种选择的优点/缺点是什么?

使用对象扩展

options = {...optionsDefault, ...options};

或者使用Object.assign

options = Object.assign({}, optionsDefault, options);

这是让我疑惑的承诺。


当前回答

我认为展开运算符和对象的最大区别。当前答案中似乎没有提到的赋值是,展开操作符不会将源对象的原型复制到目标对象。如果你想给一个对象添加属性,而你又不想改变它的实例,那么你必须使用object .assign。

编辑:实际上我已经意识到我的例子是有误导性的。展开操作符糖化为Object。将第一个参数设置为空对象进行赋值。在下面的代码示例中,我将error作为对象的第一个参数。赋值调用,所以两者是不相等的。Object的第一个参数。Assign会被修改,然后返回这就是它保留原型的原因。我在下面又加了一个例子:

const error = new Error(); error instanceof Error // true const errorExtendedUsingSpread = { ...error, ...{ someValue: true } }; errorExtendedUsingSpread instanceof Error; // false // What the spread operator desugars into const errorExtendedUsingImmutableObjectAssign = Object.assign({}, error, { someValue: true }); errorExtendedUsingImmutableObjectAssign instanceof Error; // false // The error object is modified and returned here so it keeps its prototypes const errorExtendedUsingAssign = Object.assign(error, { someValue: true }); errorExtendedUsingAssign instanceof Error; // true

参见:https://github.com/tc39/proposal-object-rest-spread/blob/master/Spread.md

其他回答

注意:Spread不仅仅是Object.assign的语法糖。它们在幕后的运作方式大不相同。

对象。assign对新对象应用setter,而Spread则不会。此外,对象必须是可迭代的。

复制 如果您需要对象当前的值,并且不希望该值反映该对象的其他所有者所做的任何更改,则使用此选项。

使用它创建对象的浅拷贝 始终将不可变属性设置为copy的好做法——因为可变版本可以传递到不可变属性中,copy将确保您始终处理不可变对象

分配 赋值在某种程度上与复制相反。 Assign将生成一个setter,它将值直接赋给实例变量,而不是复制或保留它。 当调用赋值属性的getter时,它返回一个对实际数据的引用。

我想总结一下“扩展对象合并”ES特性在浏览器和工具生态系统中的状态。

Spec

https://github.com/tc39/proposal-object-rest-spread 这个语言特性是第4阶段的提案,这意味着它已经被合并到ES语言规范中,但还没有被广泛实现。

浏览器:Chrome, SF, Firefox(60版本,IIUC)

浏览器支持Chrome 60中附带的“传播属性”,包括这个场景。 在当前的Firefox(59)中不支持此场景,但在我的Firefox开发者版中可以。所以我相信它会在Firefox 60中发布。 Safari:未测试,但Kangax说它可以在桌面Safari 11.1中运行,但不适用于SF 11 iOS Safari:未测试,但Kangax说它可以在iOS 11.3运行,但不能在iOS 11运行 还没有在Edge中

工具:Node 8.7, TS 2.1

NodeJS从8.7开始支持(通过Kangax)。9.8在本地测试时确认。 TypeScript从2.1开始支持它,目前是2.8

链接

Kangax“财产蔓延” https://davidwalsh.name/merge-objects

代码示例(兼作兼容性测试)

var x = { a: 1, b: 2 };
var y = { c: 3, d: 4, a: 5 };
var z = {...x, ...y};
console.log(z); // { a: 5, b: 2, c: 3, d: 4 }

再次强调:在编写此示例时,无需编译即可在Chrome(60+)、Firefox Developer Edition (Firefox 60预览版)和Node(8.7+)中工作。

为什么答案?

我是在最初的问题提出两年半后写这篇文章的。但我也有同样的问题,谷歌让我来这里。我是SO改善长尾理论使命的奴隶。

Since this is an expansion of "array spread" syntax I found it very hard to google, and difficult to find in compatibility tables. The closest I could find is Kangax "property spread", but that test doesn't have two spreads in the same expression (not a merge). Also, the name in the proposals/drafts/browser status pages all use "property spread", but it looks to me like that was a "first principal" the community arrived at after the proposals to use spread syntax for "object merge". (Which might explain why it is so hard to google.) So I document my finding here so others can view, update, and compile links about this specific feature. I hope it catches on. Please help spread the news of it landing in the spec and in browsers.

最后,我本可以将这些信息作为评论添加进来,但我无法在不破坏作者原始意图的情况下编辑它们。具体来说,我无法编辑@ chillpenguin的评论,否则它就会失去纠正@RichardSchulte的意图。但多年后,理查德(在我看来)证明是对的。所以我写了这个答案,希望它最终能取代旧的答案(可能需要几年时间,但毕竟这就是长尾效应的意义所在)。

太多的错误答案……

我搜索了一下,发现了很多关于这方面的错误信息。

总结

既不……扩散也不反对。赋值更快。视情况而定。 对象。如果不考虑副作用/对象突变,Assign几乎总是更快。 除了性能之外,使用这两种方法通常都没有优点或缺点,直到遇到极限情况,例如复制包含getter /setter的对象或只读属性。点击这里阅读更多。

性能

是否对象。Assign或…传播速度更快,这取决于你想要组合的东西,以及你正在使用的运行时(实现和优化不时发生)。对于小的对象,这无关紧要。

对于较大的对象,请使用Object。Assign通常更好。特别是在不需要关心副作用的情况下,只需向第一个对象添加属性就可以节省时间,而不是复制两个对象并创建一个全新的对象。看到的:

async function retrieveAndCombine() {
    const bigPayload = await retrieveData()
    const smallPayload = await retrieveData2()
    
    // only the properties of smallPayload is iterated through
    // whereas bigPayload is mutated.
    return Object.assign(bigPayload, smallPayload)
}

如果有副作用的话

在副作用很重要的情况下,例如将一个对象与另一个对象组合作为参数传入。

在下面的例子中,bigPayload将被改变,如果retrieveAndCombine之外的其他函数/对象依赖于bigPayload,这是一个坏主意。在这种情况下,可以交换传递给Object的参数。赋值,或者直接使用{}作为第一个参数来创建一个新对象:

async function retrieveAndCombine(bigPayload) {
    const smallPayload = await retrieveData2()

    // this is slightly more efficient
    return Object.assign(smallPayload, bigPayload)

    // this is still okay assuming `smallPayload` only has a few properties
    return Object.assign({}, smallPayload, bigPayload)
}

Test

试试下面的代码片段。注意:运行需要一段时间。

const rand = () => (Math.random() + 1).toString(36).substring(7) function combineBigObjects() { console.log('Please wait...creating the test objects...') const obj = {} const obj2 = {} for (let i = 0; i < 100000; i++) { const key = rand() obj[rand()] = { [rand()]: rand(), [rand()]: rand(), } obj2[rand()] = { [rand()]: rand(), [rand()]: rand(), } } console.log('Combine big objects using spread:') console.time() const result1 = { ...obj, ...obj2, } console.timeEnd() console.log('Combine big objects using assign:') console.time() Object.assign({}, obj, obj2) console.timeEnd() console.log('Combine big objects using assign, but mutates first obj:') console.time() Object.assign(obj, obj2) console.timeEnd() } combineBigObjects() function combineSmallObjects() { const firstObject = () => ({ [rand()]: rand() }) const secondObject = () => ({ [rand()]: rand() }) console.log('Combine small objects using spread:') console.time() for (let i = 0; i < 500000; i++) { const finalObject = { ...firstObject(), ...secondObject(), } } console.timeEnd() console.log('Combine small objects using assign:') console.time() for (let i = 0; i < 500000; i++) { const finalObject = Object.assign({}, firstObject(), secondObject()) } console.timeEnd() console.log('Combine small objects using assign, but mutates first obj:') console.time() for (let i = 0; i < 500000; i++) { const finalObject = Object.assign(firstObject(), secondObject()) } console.timeEnd() } combineSmallObjects()

我们将创建一个名为identity的函数,它只返回我们给它的任何参数。

identity = (arg) => arg

和一个简单的数组。

arr = [1, 2, 3]

如果用arr求恒等函数,我们知道会发生什么

展开运算符将数组展开到函数的单独参数中。

let iterableObjB = [1,2,3,4]
function (...iterableObjB)  //turned into
function (1,2,3,4)