javascript - 你如何在桌子上使用 .filter() ?
问题描述
我在桌子上使用 .filter() 时遇到了麻烦。它由 5 个单元格组成,我需要根据最后一个单元格的内容/值(索引 4)过滤表格。它有 3 个可能的值:“Node.JS”、“ReactJS”和“AngularJS”。如果用户希望为“Node.JS”过滤表,我希望删除所有表数据(仅 html,我将所有内容保存到 localStorage)并将所有包含“Node.JS”的行添加到一个新对象(filteredData)。然后我希望在新对象上调用我的 createTable 函数,但我似乎无法正确过滤它。我哪里错了?任何帮助表示赞赏(请不要使用 JQuery):)
function filterTable() {
const filterBy = document.getElementById('filter'); // filter option select
const rows = table.rows;
const savedData = JSON.parse(localStorage.getItem('data'));
let filteredData = savedData.filter(function () {
for (let i = 1; i < rows.length; i++) { // i = 1 to skip header
if (filterBy.value === 'Node.JS' && rows[i].cells[4].innerText === 'Node.JS') {
filteredData = savedData.filter(rows[i].cells[4].innerText); // I tried using return, but that only stops the function
} else if (filterBy.value === 'ReactJS' && rows[i].cells[4].innerText === 'ReactJS') {
filteredData = savedData.filter(rows[i].cells[4].innerText);
} else if (filterBy.value === 'AngularJS' && rows[i].cells[4].innerText === 'AngularJS') {
filteredData = savedData.filter(rows[i].cells[4].innerText);
}
console.log(filteredData);
}
})
}
解决方案
您以错误的方式使用过滤器。
这是一个关于如何使用的例子filter()
var array = [{name:"Alen"}, {name:"Toma"}]
var filterValue = "al"
var result = array.filter(function(x){ return x.name.toLowerCase().indexOf(filterValue.toLowerCase()) != -1})
console.log(result)
推荐阅读
- visual-studio-2015 - 尝试将数据库引用添加到引用另一个数据库的数据库得到“没有这样的源”错误
- python - python replace not na value
- azure-cosmosdb - 如何使具有 2 个分区键的文档保持同步/参照完整性?
- formal-languages - Z 表示法:如何编写可以将一个或多个元组添加到关系的操作模式
- php - Load composer scripts inside class or function
- angular - 日期晚于今天日期时显示错误
- unity3d - Unity 编辑器上的后台执行图标
- android - Firebase AuthUI:如何注册 PhoneAuthProvider OnVerificationStateChangedCallbacks
- android - 如何使用改造将数据发送到请求正文到服务器
- python - 从 github repo 下载并从 repo 导入 .py 文件以供使用