Uncaught TypeError: forEach is not a function error in javascript function
Uncaught TypeError: forEach is not a function error in javascript function
我有这个错误
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 兼容性有关
QuerySelectorAll returns 不是真正的 JS 数组的节点列表。您必须将其转换为具有所有 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 方法。
试试这个:
const trList = Array.from(document.querySelectorAll('#main_table_countries_today > tbody > tr'))
querySelectorAll()
returns一个nodeList
。使用 Array.from()
:
将其转换为数组
const trList = Array.from(document.querySelectorAll('#main_table_countries_today > tbody > tr'))'
编辑:
像这样使用 for
循环:
for (var i = 0; i < trList.length; i++) { ... }
并在其中将 tr
替换为 trList[i]
您可能需要删除一个 )
,它结束了您刚刚替换的 forEach
循环的左括号。
原回答:
尝试将代码中的第四行更改为:
Array.prototype.forEach.call(trList, function (tr, i) {
我有这个错误
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 兼容性有关
QuerySelectorAll returns 不是真正的 JS 数组的节点列表。您必须将其转换为具有所有 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 方法。
试试这个:
const trList = Array.from(document.querySelectorAll('#main_table_countries_today > tbody > tr'))
querySelectorAll()
returns一个nodeList
。使用 Array.from()
:
const trList = Array.from(document.querySelectorAll('#main_table_countries_today > tbody > tr'))'
编辑:
像这样使用 for
循环:
for (var i = 0; i < trList.length; i++) { ... }
并在其中将 tr
替换为 trList[i]
您可能需要删除一个 )
,它结束了您刚刚替换的 forEach
循环的左括号。
原回答:
尝试将代码中的第四行更改为:
Array.prototype.forEach.call(trList, function (tr, i) {