我正在尝试对每个keyup执行.filter()方法,以获取以下数组中与输入字段值匹配的对象列表:
var peopleArray = [
{
name: "Steve",
email: "steve@yahoo.com"
},
{
name: "Sam",
email: "sam@yahoo.com"
},
{
name: "Sarah",
email: "sarah@yahoo.com"
},
{
name: "Kyle",
email: "kyle@yahoo.com"
},
{
name: "Kody",
email: "kody@yahoo.com"
},
{
name: "Scarlet",
email: "scarlet@yahoo.com"
},
]
Run Code Online (Sandbox Code Playgroud)
这是我用来搜索的内容:
<input type="search" id="searchInput" placeholder="Search Activities" />
searchInput.addEventListener('keyup', function() {
searchPeople(searchInput.value);
})
function searchPeople(chars) {
//Search People and return a list of JSON objects
return //All JSON objects that matched
}
Run Code Online (Sandbox Code Playgroud)
我是新手,所以我不太明白如何实现这一目标.
如果你想要一个简单的字符串搜索,你将使用filterwith indexOf来返回包含输入的每个字符串:
function searchPeople(chars) {
return people.filter(function (person) {
return person.name.indexOf(chars) > -1;
});
}
Run Code Online (Sandbox Code Playgroud)
如果indexOf找到匹配的字符串chars,它将返回大于的位置(索引)-1.这将匹配过滤器并保留该人.
您可以展开过滤谓词来检查两者name,email如果您愿意:
function searchPeople(chars) {
return people.filter(function (person) {
return (person.name.indexOf(chars) > -1 || person.email.indexOf(chars) > -1);
});
}
Run Code Online (Sandbox Code Playgroud)