2017-04-27 79 views
0

JavaScript,第一行是错误,第二行是正确的。为什么{... undefined}不是错误,但是... undefined是错误

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

+3

'的console.log({...}未定义)',其中环境,这实际上不会产生一个错误?铬/火狐/ nodejs /巴贝尔都抱怨...意想不到 –

+1

@JaromandaX使用巴贝尔。 –

+1

@ANS - 'chrome/firefox/nodejs/babel都抱怨......意料之外 - - 什么设置? ahhh,没关系......任何阶段 - * n *似乎都可以工作 –

回答

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

是一个标准的ES6蔓延,其需要的参数是一个可迭代类型。 undefined是不可迭代的,因此你得到一个错误。

console.log({...undefined}) 

是所提出的Object spread语法。对于此语法,传入的参数将其属性复制到一个新对象中。在这种情况下,the spec defines the following

  1. 如果来源是undefinednull,让按键是一个新的空列表。

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

0

undefined可以被定义为一个对象或作为休息参数,而不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"})

相关问题