繁体   English   中英

为什么{…undefined}不是错误,但是…undefined是错误

[英]Why {…undefined} is not an error, but …undefined is an error

JavaScript,第一行是错误,第二行是正确。

console.log(...undefined) // error console.log({...undefined}) // {}

console.log(...undefined) // error

是标准的ES6扩展,要求参数为可迭代类型。 undefined是不可迭代的,因此会出现错误。

console.log({...undefined})

是建议的对象传播语法。 对于此语法,传入的参数会将其属性复制到新对象中。 在这种情况下, 规范定义了以下内容

  1. 如果source undefined或为null ,则使键为新的空List。

所以这就是为什么。 在这种情况下,它将undefined为“什么也不复制”,因此这不是错误的情况。

可以将undefined定义为对象或rest参数,而无需定义babel

 "use strict"; const fn = (...undefined) => console.log(...undefined); fn(); fn({b: 7}); fn({g: 9, x: 10}); fn({opts: "busted"}) 

使用对象余地定义babel位置

  "use strict"; const fn = ({...undefined}) => console.log({...undefined}); fn(); fn({b: 7}); fn({g: 9, x: 10}); fn({opts: "busted"}) 

尝试在定义了babel情况下重现错误,并且undefined传播元素

 "use strict"; const fn = ({...undefined}) => console.log(...undefined); // no error fn(); fn({b: 7}); fn({g: 9, x: 10}); fn({opts: "busted"}) 

暂无
暂无

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

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