簡體   English   中英

使用 Array.from 和 querySelectorAll() 有什么好處嗎

[英]Is there any advantage to using Array.from with a querySelectorAll()

在一個教程中,我看到了以下內容:

Array.from( template.querySelectorAll('.hw-text') )
  .forEach( n => n.textContent = hwMsg );

但是以下行也可以。

template.querySelectorAll('.hw-text')
  .forEach( n => n.textContent = hwMsg );

現在我想知道為什么在教程中使用 Array.from 以及從中獲得什么優勢。

forEach不是原始 NodeList 規范的一部分。 瀏覽器querySelectorAllArray.from的支持比 NodeLists 上的forEach更廣泛。

今天是否值得額外的瀏覽器支持部分取決於意見,部分取決於網站的目標受眾。

Element.querySelectorAll()返回一個NodeList這個對象有一個叫做forEach的方法,它可以讓你遍歷它的項目。

同一個NodeList對象具有length屬性,因此您可以將其傳遞給Array.from它將返回一個數組,因此您可以訪問所有數組方法,這就是他們在教程中使用它的原因。

不確定教程的意圖,但您不能在querySelectorAll()返回的 NodeList 對象上調用數組函數。

 document.querySelectorAll('.hw-text').map( ... ) // throws error
 [...document.querySelectorAll('.hw-text')].map( ... ) // works just fine
 Array.from(document.querySelectorAll('.hw-text')).map( ... ) // works just fine

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM