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

标签 javascript loops foreach graphql

我想从 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/

相关文章:

c# - 每个月的每一天

javascript - 咕噜 watch 不工作

javascript - 如何在 google chrome 中运行自己的 javascript

javascript - Angular 7 迭代表

计算字符串中数字出现的频率

c++ - 是否可以将 boost::foreach 与 std::map 一起使用?

powershell - 为什么 'continue'在Foreach-Object中的行为类似于 'break'?

javascript - Angular 2 单例列表多窗口数据共享

javascript - 我如何编写一个适用于 mousemove 事件的函数并在文档就绪时调用它?

c - 进入无限循环的简单 C 代码。为什么?