表白:黑白圣堂血天使,天劍鬼刀阿修羅。
講解對象:/Array.prototype.filter用在nodelist為什么會出現報錯
作者:融水公子 rsgz
===
Array.prototype.filter用在nodelist為什么會出現報錯
這是一個很有趣的問題,Array.prototype.filter是數組的原型方法,document.querySelectorAll('a')返回的是一個NodeList對象,不是一個數組。因此,你無法直接在NodeList上使用數組的原型方法
思路很簡單如果我們也想在nodelist對象使用這個原型方法只需要數據轉換就可以了
方式1var links = document.querySelectorAll('a'); var element = Array.from(links).filter(function(link) { return link.textContent.includes('運輸設置'); })[0]; console.log(element);
方式2var links = document.querySelectorAll('a'); var element = Array.prototype.slice.call(links).filter(function(link) { return link.textContent.includes('運輸設置'); })[0]; console.log(element);
方式3var links = document.querySelectorAll('a'); var element = Array.prototype.filter.call(links, function(link) { return link.textContent.includes('運輸設置'); })[0]; element
===公眾號:不浪仙人謝謝大家的支持!可以點擊我的頭像,進入我的空間瀏覽更多文章呢。建議大家360doc[www.360doc.com]注冊一個賬號登錄,里面真的有很多優(yōu)秀的文章,歡迎大家的到來。
---