Javascript forEach循环返回未定义的值
我有一些虚拟数据(书籍),我想从GraphiQLGUI中看到它们。但是当我使用Javascript forEach循环返回未定义的值,javascript,loops,foreach,graphql,Javascript,Loops,Foreach,Graphql,我有一些虚拟数据(书籍),我想从GraphiQLGUI中看到它们。但是当我使用forEach循环遍历书籍,寻找特定的id时,它返回未定义的值,但是如果我使用正常的for循环,它工作得很好 这是我的代码: let books = [ { name: 'Name of the Wind', genre: 'Horror', id: '1', authorID: '3' }, { name: 'The Final Empire', genre: 'Fantasy', id: '2',
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
}
}
forEach
回调中的return
没有意义。返回的值不存在,循环也不会中断
改为使用。查找:
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);
forEach
从不返回任何内容