Check if element exists in monitored array

Why does duplicate verification Artistalways return false?

Check out the JSFiddle for a demo.

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

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

+4
source share
5 answers

Not sure, but self.favoriteArtists.indexOf (newFavoriteArtist)> 0; Seems a little strange, I expect -1. If you constantly add the same artist, he will continue to think that he does not exist.

And you continue to create new objects that are not on the list. (complex) objects are not equal to each other by default.

+5
source

Your check must be one of the following:

self.favoriteArtists.indexOf(newFavoriteArtist) >= 0

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

self.favoriteArtists.indexOf(newFavoriteArtist) > -1

, . , 0, artistExists false, .

. Artist, , , , , name.

+5

, . , .

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

:

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

, (new Artist). (favoriteArtists) - .

, ( ) , .

+1
source

It is better to stop the iteration after the first element is found instead of going through the entire collection (so use find, not a filter):

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

All Articles