Jon*_*ell 4 javascript knockout.js
为什么重复检查Artist
总是返回false
?
有关可运行的演示,请参阅此JSFiddle.
淘汰赛代码
$(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());
});
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
您的支票应该是以下之一:
self.favoriteArtists.indexOf(newFavoriteArtist) >= 0
self.favoriteArtists.indexOf(newFavoriteArtist) != -1
self.favoriteArtists.indexOf(newFavoriteArtist) > -1
Run Code Online (Sandbox Code Playgroud)
你正在检查它是否大于零.这意味着如果它在位置0,artistExists
将被设置为false
因为零不大于零.
但这仍然不起作用.数组中填充的Artist
对象无法正常搜索,因为您搜索的对象与数组中的对象不同,即使它们具有相同的name
值.
不确定,但是self.favoriteArtists.indexOf(newFavoriteArtist)> 0; 看起来有点奇怪,我期待那里有-1.如果你经常添加相同的艺术家,它会一直认为它不存在.
并且你不断创建新的对象,这些对象不在列表中.(复杂)对象默认情况下彼此不相等.
归档时间: |
|
查看次数: |
21265 次 |
最近记录: |