【问题标题】:forEach loop returns undefined valueforEach 循环返回未定义的值
【发布时间】:2019-04-25 09:52:59
【问题描述】:

我有一些我想从 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
  }
}

【问题讨论】:

  • forEach 从不返回任何东西

标签: javascript loops foreach graphql


【解决方案1】:

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

改为使用.find:

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

当性能很重要,并且您有很多书籍时,最好先对书籍进行预处理并创建一个 Set:

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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-02
    • 2018-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-05
    相关资源
    最近更新 更多