为什么我的代码没有过滤数组?我缺少什么?

时间:2018-05-29 10:02:06

标签: javascript html5

这是代码
HTML:

<form>
<input type = "text" id="searchTerm" onChange="onSearchChange(this.value)" />
 </form>
<div id = "root"></div>

使用Javascript: 列表和变量声明:

 var searchItem="";
        var isFiltered;
        const list = [
  {
    title: 'React',
url: 'https://facebook.github.io/react/',
author: 'Jordan Walke',
num_comments: 3,
points: 4,
objectID: 0,
},
{
title: 'Redux',
url: 'https://github.com/reactjs/redux',
author: 'Dan Abramov, Andrew Clark',
num_comments: 2,
points: 5,
objectID: 1,
},
]

输入字段事件的功能&#39; onchange&#39;:

function onSearchChange(value){   
searchItem = value;
}

用于提取对象属性的map函数:

function extractProps(items){
    var x = "<div> <span>" +items.title+", </span> <span>"+items.author +"<span></div>"
    return x;
}

主要功能:

function myFunc(){
    document.getElementById('root').innerHTML = "";
    var y= list.filter( isFiltered = searchItem => (item) => item.title.toLowerCase().includes(searchItem.toLowerCase())).map(extractProps).join("");
    document.getElementById('root').innerHTML = y;
     alert(y);
}
myFunc()

2 个答案:

答案 0 :(得分:0)

每次调用onSearchChange时都要运行myFunc,而不是只调用一次

此外,在.filter(fn)中,fn是一个返回truthy / falsey的函数 - 而在你的代码中它返回一个真正的函数,而内部函数永远不会运行

此外,var searchItem与过滤器回调函数中的参数名称searchItem完全无关

function onSearchChange(value){   
    myFunc(value);
}

function myFunc(searchItem = ""){
    document.getElementById('root').innerHTML = "";
    var y= list.filter( item => item.title.toLowerCase().includes(searchItem.toLowerCase())).map(extractProps).join("");
    document.getElementById('root').innerHTML = y;
}

注1:您当然可以onChange="myFunc(this.value)"而不是调用一个调用具有完全相同参数的函数的函数

注2:不需要var searchItemisFiltered(无论如何都是这样?)

作为奖励,所有这些都以更现代的风格和适当的缩进重写,以使其可读

const list = [{
  title: 'React',
  url: 'https://facebook.github.io/react/',
  author: 'Jordan Walke',
  num_comments: 3,
  points: 4,
  objectID: 0,
}, {
  title: 'Redux',
  url: 'https://github.com/reactjs/redux',
  author: 'Dan Abramov, Andrew Clark',
  num_comments: 2,
  points: 5,
  objectID: 1,
}];

const extractProps = ({title, author}) => `<div><span>${title}, </span> <span>${author}<span></div>`;

document.getElementById('searchTerm').addEventListener('change', function() {
  myFunc(this.value.toLowerCase());
});
const myFunc = (searchItem = '') => document.getElementById('root').innerHTML = list
  .filter(item => item.title.toLowerCase().includes(searchItem))
  .map(extractProps)
  .join("");


myFunc();
<form>
  <input type="text" id="searchTerm" />
</form>
<div id="root"></div>

答案 1 :(得分:-1)

By using $.map() you can achieve this.
Provide array of objects(here list) and call back function.

function myFunc(){
    var fillteredArr = $.map( list, function( val, i ) {
         if(val.title.toLowerCase() == searchItem.toLowerCase())
            return val;
    });
    return fillteredArr;
}

The function myFunc() will return the filltered array of objects.