Knockout Observable Array IndexOf method


cityArray.indexOf(data.results[index].City) === -1

如何使用indexOf方法进行挖空可观察数组,其中每个项目都是一个对象? cityArray包含具有称为City的属性的对象。

谢谢大家的回答。我试图使用 indexOf 方法来查看可观察数组中是否已经存在一个条目。相反,我现在使用 ko.utils.arrayGetDistinctValues,所以我不再需要使用 indexOf 方法。但是由于arrayGetDistinctValues不适用于对象数组,我首先将值复制到普通数组中,然后在其上使用函数。

cityArray.indexOf(    
    ko.utils.arrayFirst(ko.utils.unwrapObservable(cityArray), function(cityObj) {
        return ko.utils.unwrapObservable(cityObj.City) == 'WallaWalla';
    }
)

ko.utils.unwrapObservable 函数在需要时将 () 您的对象,如果不需要,则不会。轻。。。在 V2.3 中,你可以只做 ko.unwrap,以防万一你担心 js 中有太多字母。

array首先返回对象,然后 indexOf 将拉取对象的比较,如果它不存在,你应该得到你的索引...-1...如果与 arrayFirst 没有匹配项,则得到 null。

这就是我让我的arrayIndexOf工作的方式

var viewModel = function() {
  var self = this;
  self.suggestions = ko.observableArray([]);
  self.filterText = ko.observable('');
  self.filterText.subscribe(function(newValue) {});
  self.suggestionsFilter = ko.computed(function() {
    
    if (self.filterText() === '') {
      return self.suggestions();
    } else {
      return ko.utils.arrayFilter(self.suggestions(), function(item) {
        var filterResults = item.option.toLowerCase().indexOf(self.filterText().toLowerCase()) == 0;
        return filterResults;
      });
    }
  });
};
<div class="col-md-6 postcode-search" id="js-postcode-search-suggestions">
  <input id="name-search" class="form-control" type="search" name="postcode" minlength="1" placeholder="Postcode or Address" data-bind="textInput: filterText" />
  <div class="col-md-12" data-bind="visible: suggestions().length > 1" style="display: none">
    <ul class="suggestions" data-bind="foreach: suggestionsFilter">
      <li class="pad-top-bottom">
        <a href="#">
          <span class="option" data-bind="html: option"></span>
        </a>
      </li>
    </ul>
  </div>
</div>

最新更新