首页 > 解决方案 > 搜索子字符串淘汰js

问题描述

我正在尝试过滤一个数组并检查我的数组中的任何标题是否包含用户正在搜索的内容。但是,当我运行该函数时,它似乎只检查搜索是否与标题完全匹配,而不是是否包含子字符串。

JS

var viewModel = function() {
var self = this;
self.filter = ko.observable('');
self.locationList = ko.observableArray(model);
self.filterList = function(){

    return ko.utils.arrayFilter(model, function(location) {

       if(self.filter().includes(location.title)){
          console.log(location.title)
       }

    });
  };
}

HTML

<div class="col-lg-12">
  <div class="input-group">
    <input data-bind="textInput: filter, event:{keyup: filterList}"
    type="text" class="form-control" placeholder="Filter Places"
    aria-describedby="basic-addon2" id="test">
    <button id="basic-addon2">Filter</button>
   </div>
 </div>

标签: javascripthtmlknockout.jsdata-binding

解决方案


问题出在这部分if(self.filter().includes(location.title)){

在这里,您正在检查搜索的键是否包含数组中的标题之一。相反,您应该另外检查

if(location.title.includes(self.filter())){

你可以使用简单.filter.includes

var filterdList = self.locationList.filter(e=> e.includes(self.filter()))

推荐阅读