当我传递标题和作者的值时,我想首先检查是否存在具有相同标题的任何其他值。如果存在,则不要向空数组中输入数据,如果不存在,则输入数据。但我得到 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/