[英]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})
是建議的對象傳播語法。 對於此語法,傳入的參數會將其屬性復制到新對象中。 在這種情況下, 規范定義了以下內容 :
- 如果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.