我正在尝试过滤数组以使用express打印已读书籍,但无法读取或结果为空

问题描述 投票:0回答:1

我有一个书单,并尝试打印出那些已经以“作者标题”形式阅读过的书

const bookList = [
    {title: "Harry Potter", author: "J.K. Rowling", alreadyRead: true},
    {title: "Never Eat Alone", author: "Keith Ferrazzi", alreadyRead: false},
    {title: "INSPIRED", author: "Marty Cagan", alreadyRead: false},
    {title: "Zero to One", author: "Peter Thiel", alreadyRead: true}
]

首先,我通过传递书单和状态来使用此 for 循环方法来调用函数

printBookList(bookList, true)
,但最终会打印列表中的所有元素

function printBookList(bookList, completedReadingBook){
    for(i=0;i<bookList.length;i++){
        if (bookList[i].alreadyRead == completedReadingBook) {
            console.log(bookList[i].title + ' by ' + bookList[i].author);
        }
    }  
}

然后我也尝试使用下面的

filter()
方法,但最终显示为空

for(i=0; i<bookList.length;i++){
    let filtered = bookList.filter((readbook)=>readbook.alreadyRead==completedReadingBook)
    return filtered;
    }
    console.log(bookList[filtered].title + ' by ' + bookList[filtered].author);

我对这个js很陌生,如果有人可以向我解释这一点,我将不胜感激,非常感谢!

javascript arrays for-loop filter
1个回答
0
投票

正如 Jaromanda X 指出的:

  • 你的第一个简单的 for 循环函数应该可以正常工作;
  • Array.filter()
    是调用整个数组的方法;
  • 不确定你的第二段代码是否在函数内部,但如果是,确实最后一行(
    console.log()
    )永远不会被执行,因为它位于
    return
    语句之后;如果不是,那么
    return
    语句不应该存在;
  • filtered
    是一个数组,而不是索引,因此
    bookList[filtered]
    是不正确的语义。

您可以阅读

Array.filter()
here上的文档,您的第二段代码应该如下所示:

function printBooklist(bookList, completedReadingBook) {
  const filtered = bookList.filter((readbook)=>readbook.alreadyRead==completedReadingBook);
  for(i=0; i<bookList.length;i++){
    console.log(filtered[i].title + ' by ' + filtered[i].author);
  }
}

您还可以使用内置的 JS 方法,例如

Object.groupBy
forEach
:

function printReadBooks() {
  const bookList = [
    {title: "Harry Potter", author: "J.K. Rowling", alreadyRead: true},
    {title: "Never Eat Alone", author: "Keith Ferrazzi", alreadyRead: false},
    {title: "INSPIRED", author: "Marty Cagan", alreadyRead: false},
    {title: "Zero to One", author: "Peter Thiel", alreadyRead: true}
  ];
  // Object.groupBy returns an object grouped by the alreadyRead property.
  const readBooks = Object.groupBy(bookList, ({alreadyRead}) => alreadyRead).true;
 
  console.log("Already read books:");
  readBooks.forEach(({title, author}) => console.log(` - ${title}, by ${author};\n`));
 
  /* The following line will only work in some environments:
  readBooks.forEach(({title, author}) =>
                    console.log(` - %c${title}%c, by ${author};\n`,
                                "font-style: italic", "font-style: normal")); */
}

printReadBooks();

© www.soinside.com 2019 - 2024. All rights reserved.