javascript - 数组显示未定义作为答案而不是显示对象值

标签 javascript arrays

当我传递标题和作者的值时,我想首先检查是否存在具有相同标题的任何其他值。如果存在,则不要向空数组中输入数据,如果不存在,则输入数据。但我得到 undefined 作为答案。我哪里做错了。

var add = (title, author) => {
  var i = 0;
  var notes = [];
  var note = {
    title,
    author
  };

  for (i = 0; i < notes.length; i++) {
    if (note.title === notes[i].title) {
      console.log('same entry');
    } else {
      notes.push(note);
    }
  };
  
  console.log(notes[i]);
};

add("TITLE", "AUTHOR")

最佳答案

你需要做一个全局的notes,因为每次调用这个数组都是空的。然后,如果您发现具有相同 title 的条目,则需要返回该函数。

如果在数组中找不到标题,最后推送一个新对象。

var notes = [],                              // global or outside of the function
    add = (title, author) => {
        var i;
        for (i = 0; i < notes.length; i++) {
            if (title === notes[i].title) {  // check title
                console.log('same entry');
                return;                      // exit function if title exists
            }
        };
        notes.push({ title, author });       // no title found, add new object
    };
    
console.log(notes);

add('a', 'b');
console.log(notes);

add('a', 'b');
console.log(notes);

add('c', 'd');
console.log(notes);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 数组显示未定义作为答案而不是显示对象值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54968995/

相关文章:

javascript - 通过正则表达式从字符串中提取 URL

c - 声明指向函数返回数组的指针实际上是合法的吗?

c# - 当 CopyTo 非静态方法的目标和源是同一个数组时,如何可能发生重叠?

javascript - 按键数对对象数组进行排序 (JavaScript)

javascript - jQuery Select # id with word 作为前缀和 counter 作为后缀

javascript - 有没有办法限制 Meteor aldeed 表格包中发布的字段

javascript - jquery window.scroll 函数内的变量范围问题

c++ - 当需要数组时,将指针传递给 vector 中的第一个元素是否安全?

在 C 中清除 char 数组

javascript - 如何为erb设置<a title ="">?