未定义的Javascript ES6传播运算符 [英] Javascript ES6 spread operator on undefined

查看:157
本文介绍了未定义的Javascript ES6传播运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在开发我的React App时,我需要向组件发送条件道具,因此我在某处找到了一种模式来进行操作,尽管这对我来说似乎真的很奇怪,我无法理解它的工作方式和原因.

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.

如果我输入:

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.

对于这种行为,我感到很惊讶,这真的是应该的吗?我可以依靠它吗?这是一种好习惯吗?

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?

推荐答案

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

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
  } 
}

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

这篇关于未定义的Javascript ES6传播运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆