Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/465.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript forEach循环返回未定义的值_Javascript_Loops_Foreach_Graphql - Fatal编程技术网

Javascript forEach循环返回未定义的值

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',

我有一些虚拟数据(书籍),我想从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', 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
从不返回任何内容