首页 > 解决方案 > 你如何在桌子上使用 .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);
            }
        })
    }

标签: javascriptfilter

解决方案


您以错误的方式使用过滤器。

这是一个关于如何使用的例子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)


推荐阅读