如何有条件地将项目推送到可观察数组中? [英] How to conditionally push an item in an observable array?

查看:42
本文介绍了如何有条件地将项目推送到可观察数组中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将新项目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函数可以接收传递条件的函数.我几乎想要相同的功能,但仅在传入的条件为true或不为true时才推送它.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆