为什么检查重复的
请参考此JSFiddle示例。 Knockout 代码:
Artist
总是返回false
?请参考此JSFiddle示例。 Knockout 代码:
$(function() {
function Artist(name) {
this.name = name;
}
function ViewModel() {
var self = this;
self.favoriteArtists = ko.observableArray([]);
self.artistToAdd = ko.observableArray("");
self.addArtist = function () {
var newFavoriteArtist = new Artist(self.artistToAdd());
console.log("New Favorite Artist: " + newFavoriteArtist.name);
var artistExists = self.favoriteArtists.indexOf(newFavoriteArtist) > 0;
console.log("Artist Exists: " + artistExists);
if(!artistExists) {
self.favoriteArtists.push(newFavoriteArtist);
console.log("A new artist has been added:" + self.artistToAdd());
} else {
console.log("Artist already in favorites.");
}
};
}
ko.applyBindings(new ViewModel());
});
HTML
<h1>Favorite Artists</h1>
<p>Currently, your favorite artists include:</p>
<ul data-bind="foreach: favoriteArtists">
<li> <span data-bind="text: name"></span>
</li>
</ul>
<p>Enter the name of a new artist:</p>
<input data-bind="value: artistToAdd" />
<button data-bind="click: addArtist">Add</button>
observableArray
? - KSFTself.artistToAdd
应该是ko.observable("")
而不是ko.observableArray("")
,这就是导致检查始终返回 false 的原因。 - Jonathan KittellfavoriteArtists
是一个observableArray
而不是普通数组? - KSFTArtist
项目列表。 - Jonathan Kittell