[我正在尝试编写一个接受输入(库,authorName)并返回作者写书名的程序。
该库看起来像这样:
let library = [
{ author: 'Bill Gates', title: 'The Road Ahead', libraryID: 1254 },
{ author: 'Carolann Camilo', title: 'Eyewitness', libraryID: 32456 },
{ author: 'Carolann Camilo', title: 'Cocky Marine', libraryID: 32457 }
];
我的代码如下:
let library = [
{ author: 'Bill Gates', title: 'The Road Ahead', libraryID: 1254 },
{ author: 'Carolann Camilo', title: 'Eyewitness', libraryID: 32456 },
{ author: 'Carolann Camilo', title: 'Cocky Marine', libraryID: 32457 }
];
function searchBooks(library, author) {
for (author in library) { //enumerate
if (author in library) {
let line = Object.values(library[0]) // find line of the wanted author
let result = (line[0] + "," + line[1]) // store author name and title name
return result
} else {
return "NOT FOUND"
}
}
}
console.log(searchBooks(library, 'Bill Gates'))
输出看起来像这样:Bill Gates,The Road Ahead
该问题:无论我将输入searchBook
的作者是什么,它都会返回库的第一行Bill Gates。因此,我猜并不能一一列举。但是为什么不呢?
我首先想到也许我必须避免对[0]和[1]进行硬编码,而是使用i和i ++。但这似乎也不起作用,因为它随后输出TypeError: Cannot convert undefined or null to object
几件事:
for (author in library)
正在查找库数组的每个键,而使用of
来评估每个值。由于它是一个对象,因此我将该值命名为book
result
可能有很多值,因此最好使其成为某种数组或集合,您可以在其中堆叠响应]if (author in library)
检查您的作者是否是原始库数组中的键,这也是不希望的。您真的想查看author
是否是对象的值。更具体地说,您希望您的作者是对象的作者键的值。所以book.author == author
NOT FOUND
消息。否则,您想退回所有书籍let library = [
{ author: 'Bill Gates', title: 'The Road Ahead', libraryID: 1254 },
{ author: 'Carolann Camilo', title: 'Eyewitness', libraryID: 32456 },
{ author: 'Carolann Camilo', title: 'Cocky Marine', libraryID: 32457 }
];
function searchBooks(library, author) {
let result = []
for (let book of library) {
if (book.author == author) {
let line = Object.values(book) // find line of the wanted author
result.push(line[0] + "," + line[1]) // store author name and title name
}
}
return result.join('\n') || 'NOT FOUND'
}
console.log(1, searchBooks(library, 'Carolann Camilo'))
console.log(2, searchBooks(library, 'Bill Gates'))
console.log(3, searchBooks(library, 'Oh boy'))
注意:
Object.values
的方法,请参见this answerfilter
遍历库的方法,请寻求this answerforEach
,请寻找this answer您可能想使用Array.filter
(see MDN):
const library = [
{ author: 'Bill Gates', title: 'The Road Ahead', libraryID: 1254 },
{ author: 'Carolann Camilo', title: 'Eyewitness', libraryID: 32456 },
{ author: 'Carolann Camilo', title: 'Cocky Marine', libraryID: 32457 }
];
console.log(findAuthor(library, `Bill Gates`));
function findAuthor(library, author) {
return library.filter(book => book.author === author);
}
您可以使用forEach遍历元素并将它们添加到给定结果中,以用于同一作者的多个条目。>
let library = [
{author: 'Bill Gates', title: 'The Road Ahead', libraryID: 1254 },
{ author: 'Carolann Camilo', title: 'Eyewitness', libraryID: 32456 },
{ author: 'Carolann Camilo', title: 'Cocky Marine', libraryID: 32457 }
];
function search(library, author) {
let result = ""
library.forEach(l => {
if (l.author === author) {
result += l.author+", "+l.title+"\n"
}
})
return result
}
console.log(search(library, "Carolann Camilo"))
这是您的方法的有效版本: