[英]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 規范的一部分。 瀏覽器對querySelectorAll
和Array.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.