2016-12-28 36 views
0

我知道querySelectorAll返回類似於數組的數組,但不完全是數組。所以,在我的代碼我使用ES6傳播語法遍歷它:數組傳播符號應該如何與巴別克的NodeLists一起使用?

const things = document.querySelectorAll('.things'); 
[...things].forEach(thing => thing.do()); 

如果我寫的是確切的代碼到瀏覽器devtools控制檯,它按預期工作。然而,巴貝爾是transpiling到ES5:

var things = document.querySelectorAll('.things'); 
[].concat(things).forEach(function(thing) { thing.do() }); 

[].concat(things)一樣做[...things]。預期結果是一組節點,但concat返回一個NodeLists數組。因此調用thing.do()會導致錯誤,因爲NodeList沒有do方法。

相反,在NodeList上使用Array方法的ES5友好方式將首先調用slice,如Array.prototype.slice.call(things)

因此,Babel錯誤地將數據傳播的每一次使用都編譯爲concat?或者是否有我錯過的更新版本或配置?

+0

你需要什麼瀏覽器支持? –

+1

聽起來像你在你的Babel預設中使用'loose:true',這會禁用你正在尋找的行爲。 – loganfsmyth

+0

只需要支持常青樹瀏覽器 –

回答

0

您可以將NodeList.prototype上的@@isConcatSpreadable屬性設置爲true,以使其與[].concat正常工作。

NodeList.prototype[Symbol.isConcatSpreadable] = true; 
 
const divs = document.querySelectorAll('div'); 
 
console.log([].concat(divs));
<div>foo</div> 
 
<div>bar</div>

相關問題