如果不为空则创建新条目,并且不存在重复项

时间:2017-03-30 07:03:22

标签: javascript jquery

如果

,我想创建一个带标题和文字的笔记
  • 标题不为空
  • 标题尚不存在

当我在数组中检查重复项时,它总是返回true,即使存在重复项。

我的代码:

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));
  }

那么第二次检查有什么问题=?

由于

2 个答案:

答案 0 :(得分:1)

您不是要将标题与其他音符标题进行比较,而是将其与音符对象进行比较。

假设标题在注释对象上显示为title属性,则必须重写这样的条件:

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

或者使用标准的JavsScript:

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

答案 1 :(得分:0)

检查{console.log($。inArray(title,this.store.notes))}中的值。 或者使用其他条件$ .inArray(title,this.store.notes)=== -1。 希望这可以解决问题。