gpt4 book ai didi

javascript - 检查一个项目是否存在于 observableArray 中

转载 作者:搜寻专家 更新时间:2023-11-01 04:48:30 26 4
gpt4 key购买 nike

为什么检查重复的 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>

最佳答案

您的支票应该是以下之一:

self.favoriteArtists.indexOf(newFavoriteArtist) >= 0

self.favoriteArtists.indexOf(newFavoriteArtist) != -1

self.favoriteArtists.indexOf(newFavoriteArtist) > -1

您正在检查它是否大于零。这意味着如果它位于位置 0,artistExists 将被设置为 false,因为零不大于零。

不过,这仍然行不通。数组中填充的是Artist对象,不能正常搜索,因为你搜索的对象和数组中的对象不一样,即使它们有相同的name 值。

关于javascript - 检查一个项目是否存在于 observableArray 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29583225/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com