gpt4 book ai didi

javascript - forEach 循环返回未定义的值

转载 作者:行者123 更新时间:2023-11-30 11:05:25 24 4
gpt4 key购买 nike

我想从 graphiql gui 中查看虚拟数据(书籍)。但是当我使用 forEach 循环遍历书籍,寻找特定的 id 时,它会返回未定义的值,但是如果我使用普通的 for 循环它工作正常。

这是我的代码:

let books = [
{ name: 'Name of the Wind', genre: 'Horror', id: '1', authorID: '3' },
{ name: 'The Final Empire', genre: 'Fantasy', id: '2', authorID: '1' },
{ name: 'The Long Earth', genre: 'Sci-Fi', id: '3', authorID: '2' },
];
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
book: {
type: BookType,
args: { id: { type: GraphQLString } },
//this forEach is not working
resolve(parent, args){
books.forEach( function(book) {
if(book.id == args.id) {
console.log(book);
return book;
}
});
}
}
}
});

当我打印图书数据时,它在控制台中显示了该特定图书,但在 GUI 响应中没有显示:

request:
{
book(id: "2") {
name
genre
}
}
response:
{
"data": {
"book": null
}
}

最佳答案

A return <value>forEach回调没有意义。返回值无处可去,循环也没有中断。

改为使用 .find :

return books.find(function(book) {
return book.id == args.id;
});

当性能很重要并且你有很多书时,最好先预处理这些书并创建一个集合:

let books = [
{ name: 'Name of the Wind', genre: 'Horror', id: '1', authorID: '3' },
{ name: 'The Final Empire', genre: 'Fantasy', id: '2', authorID: '1' },
{ name: 'The Long Earth', genre: 'Sci-Fi', id: '3', authorID: '2' },
];
let bookIds = new Set(books.map(({id}) => id));

...然后不需要循环就可以知道图书 ID 是否有效:

return bookIds.has(args.id);

关于javascript - forEach 循环返回未定义的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55846490/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com