[英]Why {…undefined} is not an error, but …undefined is an error
JavaScript,第一行是错误,第二行是正确。
console.log(...undefined) // error console.log({...undefined}) // {}
console.log(...undefined) // error
is a standard ES6 spread, which requires the argument to be an iterable types. 是标准的ES6扩展,要求参数为可迭代类型。
undefined
is not iterable, thus you get an error. undefined
是不可迭代的,因此会出现错误。
console.log({...undefined})
is the proposed Object spread syntax. 是建议的对象传播语法。 For this syntax, the argument passed in will have its properties copied into a new object.
对于此语法,传入的参数会将其属性复制到新对象中。 In this case, the spec defines the following :
在这种情况下, 规范定义了以下内容 :
- If source is
undefined
ornull
, let keys be a new empty List.如果source
undefined
或为null
,则使键为新的空List。
so that's why. 所以这就是为什么。 In this case, it sees
undefined
as "copy nothing", so it is not an erroneous case. 在这种情况下,它将
undefined
为“什么也不复制”,因此这不是错误的情况。
undefined
can be defined as an object or as a rest parameter, without babel
being defined 可以将
undefined
定义为对象或rest参数,而无需定义babel
"use strict"; const fn = (...undefined) => console.log(...undefined); fn(); fn({b: 7}); fn({g: 9, x: 10}); fn({opts: "busted"})
Where babel
is defined, using object rest 使用对象余地定义
babel
位置
"use strict"; const fn = ({...undefined}) => console.log({...undefined}); fn(); fn({b: 7}); fn({g: 9, x: 10}); fn({opts: "busted"})
Attempt to reproduce error where babel
is defined and spread element precedes undefined
尝试在定义了
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.