简体   繁体   中英

Create new entry if not empty and no duplicates exist

I want to create a note with a title and a text if

  • the title is not empty
  • the title does not already exist

When I check for duplicates in my array, it always returns true, even if there are duplicates.

My code:

CreateNote(title, text){
    if (title.length > 0 && // title is empty?
 $.inArray(title, this.store.notes) < 0) // check the array for duplicates, returns always true, even with duplicates in the store
      this.store.AddNote(new Note(title, text));
  }

So what is wrong with the second check =?

Thanks

You're not comparing the title to the other note titles, but instead to the note objects.

Assuming that the title is exposed as a title property on the note objects, you'd have to rewrite your condition like this:

$.inArray(title, this.store.notes.map(n => n.title)) < 0

Or with standard JavsScript:

!this.store.notes.some(n => n.title === title)

Check the value in {console.log($.inArray(title, this.store.notes))}. or use other way of condition $.inArray(title, this.store.notes) === -1. Hope this might solve the issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM