An observableArray exposes an indexOf
function (wrapper to ko.utils.arrayIndexOf
). This allows you to do:
if (myObservableArray.indexOf(itemToAdd) < 0) {
myObservableArray.push(itemToAdd);
}
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);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…