我在KnockoutObservableArray下面。我要搜索和检索此数组中仅有的前5个结果。
var people: KnockoutObservableArray<string>;
this.people.push("abc");
this.people.push("aaa");
this.people.push("xyz");
...
我使用people.filter方法尝试了多个选项,但找不到确切的要求。
有人可以在这里帮我吗?
答案 0 :(得分:0)
不完全确定搜索数组的意思。如果您想对数组项进行某种测试,而只检索通过的项,那么ko.utils.arrayFilter是可行的方法。
一个过滤数组的示例,仅返回与另一个可观察到的值匹配的值:
self.KeyWorkerFilter = ko.observable('');
self.KeyWorkersFiltered = ko.computed(function () {
// if the filter is blank then just return the whole collection
if (!self.KeyWorkerFilter || self.KeyWorkerFilter() === '') {
return self.TpwKeyWorkers();
}
var filteredKeyWorkers = ko.utils.arrayFilter(self.TpwKeyWorkers(), function (item) {
var name = item.name.toLowerCase();
return name.includes(self.KeyWorkerFilter().toLowerCase());
});
return filteredKeyWorkers;
});
所以在您的情况下,您可能会做类似的事情
var.peopleFilter = ko.computed(function() {
return ko.utils.arrayFilter(this.people, function(item) {
// whatever your test is
// example: only return array items that are equal to "aaa"
item === "aaa";
});
});
答案 1 :(得分:0)
您可以像这样创建一个computed
属性,该属性将基于searchText
filter
这个数组。然后使用slice
获得前5个结果:
在输入中搜索“ a”,直到“ ae”,您才能看到结果。
let viewModel = function() {
let self = this;
self.people = ko.observableArray(["aa", "ab", "ac", "ad", "ae", "af", "ag"]);
self.searchText = ko.observable('');
// When "searchText" or "people" changes, this gets computed again
self.filteredPeople = ko.computed(function() {
if (!self.searchText() || !self.searchText().trim()) {
return [];
} else {
return self.people()
.filter(p => p.toLowerCase().indexOf(self.searchText().toLowerCase()) > -1)
.slice(0, 5);
}
});
};
ko.applyBindings(new viewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<input type="text" data-bind="value: searchText, valueUpdate: 'keyup'" placeholder="Search...">
<div data-bind="foreach:filteredPeople">
<span data-bind="text:$data"></span><br>
</div>