如何有条件地推送可观察数组中的项目? [英] How to conditionally push an item in an observable array?
问题描述
我想将一个新项目push
到一个observableArray
,但前提是该项目尚不存在.在 KnockoutJS 中是否有任何查找"功能或推荐的模式来实现这一点?
I would like to push
a new item onto an observableArray
, but only if the item is not already present. Is there any "find" function or recommended pattern for achieving this in KnockoutJS?
我注意到 observableArray
上的 remove
函数可以接收传递条件的函数.我几乎想要相同的功能,但只有在传入的条件为真或不为真时才推送它.
I've noticed that the remove
function on an observableArray
can receive a function for passing in a condition. I almost want the same functionality, but to only push it if the condition passed in is or is not true.
推荐答案
一个 observableArray 公开了一个 indexOf
函数(封装到 ko.utils.arrayIndexOf
).这允许您执行以下操作:
An observableArray exposes an indexOf
function (wrapper to ko.utils.arrayIndexOf
). This allows you to do:
if (myObservableArray.indexOf(itemToAdd) < 0) {
myObservableArray.push(itemToAdd);
}
如果这两个实际上不是对同一个对象的引用,并且您想运行自定义比较逻辑,那么您可以使用 ko.utils.arrayFirst
像:
If the two are not actually a reference to the same object and you want to run custom comparison logic, then you can use ko.utils.arrayFirst
like:
var match = ko.utils.arrayFirst(myObservableArray(), function(item) {
return itemToAdd.id === item.id;
});
if (!match) {
myObservableArray.push(itemToAdd);
}
这篇关于如何有条件地推送可观察数组中的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!