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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29583225/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:36:57  来源:igfitidea点击:

Check if an item exists in an observableArray

javascriptknockout.js

提问by Jonathan Kittell

Why is the check for duplicate Artistalways returning false?

为什么重复检查Artist总是返回false

See this JSFiddlefor a runnable demo.

请参阅此JSFiddle以获取可运行的演示。

Knockout Code

淘汰码

$(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

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>

回答by KSFT

Your check should be one of these:

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

self.favoriteArtists.indexOf(newFavoriteArtist) >= 0

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

self.favoriteArtists.indexOf(newFavoriteArtist) > -1

You're checking whether it's greater than zero. That means that if it's in position 0, artistExistswill be set to falsebecause zero is not greater than zero.

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

That still doesn't work, though. The array is filled with Artistobjects, which can't be searched for normally, because the object you search for is different from the object in the array, even if they have the same namevalue.

但是,这仍然不起作用。数组中塞满了Artist对象,通常无法搜索到,因为搜索的对象与数组中的对象不同,即使它们具有相同的name值。

回答by Johan

Not sure, but self.favoriteArtists.indexOf(newFavoriteArtist) > 0; seems a bit strange, I expect a -1 there. If you add the same artist constantly it will keep thinking it did not exist.

不确定,但 self.favoriteArtists.indexOf(newFavoriteArtist) > 0; 似乎有点奇怪,我希望那里有 -1。如果你不断添加同一个艺术家,它会一直认为它不存在。

And you keep making new objects, that are not in the list. (complex) objects are not equal to eachother by default.

并且您不断制作不在列表中的新对象。默认情况下,(复杂)对象彼此不相等。

回答by David Skowronski

You can filter the array and check to see if its length is zero. If it is not empty, it contains the item.

您可以过滤数组并检查其长度是否为零。如果它不为空,则它包含该项目。

return favoriteArtists.filter(function(data) {
      return data === newFavoriteArtist;
    }).length !== 0;

回答by Vladimir Posvistelik

Take a look at this part of code:

看看这部分代码:

var newFavoriteArtist = new Artist(self.artistToAdd());
// ...
var artistExists = self.favoriteArtists.indexOf(newFavoriteArtist) > 0;

Each time you create a new object (new Artist). Then you're trying to find new object in a list of old objects (favoriteArtists) - and here your code doesn't work as expected.

每次创建新对象时 ( new Artist)。然后,您尝试在旧对象 ( favoriteArtists)列表中查找新对象- 此处您的代码无法按预期工作。

Instead you could add some another function, which allows you to find artist by name (or some other unique property) and clarify whether this item was added before.

相反,您可以添加一些其他功能,它允许您按名称(或其他一些唯一属性)查找艺术家,并说明此项目之前是否已添加。

回答by wally

Better is to stop iterating after first element is found instead of go through all collection (so use find, not filter):

更好的是在找到第一个元素后停止迭代,而不是遍历所有集合(因此使用查找,而不是过滤器):

return favoriteArtists.find(function(data) {
  return data === newFavoriteArtist;
}) !== null;