首页 > 解决方案 > 未捕获的 TypeError:forEach 不是 javascript 函数中的函数错误

问题描述

我有这个错误

Uncaught TypeError: trList.forEach is not a function

在这个函数中

function findMatchingRow(word) {
   const found = []
   const trList = document.querySelectorAll('#main_table_countries_today > tbody > tr')
   trList.forEach(function(tr, i) {
       if(tr.textContent.match(word)) {
           found.push({index: i, content: tr.textContent})
       }
       })
       return found
   }

{const matches = findMatchingRow('Tunisia')
 console.log(matches)
 if(matches.length > 0) {
     console.log('found at:', matches.map(function(m) { return m.index; }))}}

我认为这个问题与 ES6 兼容性有关

标签: javascriptandroidjquerywebview

解决方案


QuerySelectorAll 返回一个不是真正的 JS 数组的 nodeList。您必须将其转换为具有所有 Array 方法的真正 JS Array。

我创建了一个实用函数来为我做这件事。

 function nodeListToArray(elem){
    return [].slice().call(elem);
 }

然后你像这样使用它。

const trList = document.querySelectorAll('#main_table_countries_today > tbody > tr');
const trArr = nodeListToArray(trList);

“trArr”将具有 forEach 方法。


推荐阅读