2017-04-27 78 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"})

相關問題