未定义的 Javascript ES6 扩展运算符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46957194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:41:27  来源:igfitidea点击:

Javascript ES6 spread operator on undefined

javascriptecmascript-6javascript-objectsspread-syntax

提问by omri_saadon

While developing my react App, I needed to send a conditional prop to a component so I found somewhere a pattern to do so, although it seems really weird to me and I couldn't understand how and why it worked.

在开发我的 React 应用程序时,我需要向组件发送一个条件道具,所以我在某处找到了一个模式来这样做,尽管对我来说这看起来很奇怪,我无法理解它是如何以及为什么工作的。

If I type:

如果我输入:

console.log(...undefined)   // Error 
console.log([...undefined]) // Error
console.log({...undefined}) // Work

When the spread operator is activated on undefined an error is raised, although when the undefined is inside an object, an empty object returned.

当在 undefined 上激活扩展运算符时会引发错误,但当 undefined 在对象内时,会返回一个空对象。

I'm quite surprised regarding this behavior, is that really how it supposed to be, can I rely on this and is that a good practice?

我对这种行为感到非常惊讶,它真的应该是这样吗,我可以依靠这个吗,这是一个很好的做法吗?

回答by strider

This behavior is useful for doing something like optional spreading:

此行为对于执行诸如可选传播之类的操作很有用:

function foo(options) {
  const bar = {
    baz: 1, 
    ...(options && options.bar) //options and bar can be undefined
  } 
}

And it gets even better with optional chaining, which is in stage-1:

并且通过可选链接变得更好,它位于stage-1

function foo(options) {
  const bar = {
    baz: 1, 
    ...options?.bar //options and bar can be undefined
  } 
}

a thought: its too bad it doesn't also work for spreading into an array

一个想法:太糟糕了它也不能传播到数组中