javascript - 未捕获的 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 兼容性有关
解决方案
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 方法。
推荐阅读
- ios - 没有使用 pod 的模块“SDWebImage”
- python-3.x - 解析包含在 python 3.x 中以不同顺序排列的不同字段的字符串
- xamarin.forms - Error:Xamarin.Forms targets have been imported multiple times
- python - need to convert List output to a dictionary or preferable json. Please suggest
- php - PHP responses nothing when requesting from iOS App (Swift)
- javascript - 告诉 npm 在特定文件夹中查找 package.json
- woocommerce - 结帐 - 根据地理位置限制计费和运输中的国家/地区
- ssis - Attunity 连接器未在 VS 2017、SQL Server 2017 的 SSIS 中显示
- jquery - 查找页面中的所有 datetimepicker 控件
- c# - ContainerFromItem() 从绑定对象中选择 GridViewItem