我正在尝试编写一个程序,该程序接受输入(库,authorName)并返回作者写的书的标题。
该库如下所示:
let library = [
{ author: 'Bill Gates',title: 'The Road Ahead',libraryID: 1254 },{ author: 'Carolann Camilo',title: 'Eyewitness',libraryID: 32456 },title: 'Cocky Marine',libraryID: 32457 }
];
我的代码如下:
let library = [
{ author: 'Bill Gates',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