ジャンルで絞り込み
CoddyのJavaScriptジャーニー「論理とフロー」セクションの一部。レッスン 45/65。
チャレンジ
簡単switch文に新しいケースfilterByGenreを追加してください。このアクションは、本をジャンルでフィルタリングするものです。
filterByGenreケースの手順は以下の通りです:
currentDataパラメータは、フィルタリングするジャンルを表す文字列です- フィルタリングされた結果を格納するための空の配列
filteredResultsを作成します - ライブラリ内のすべての本をループで処理します
- 各本について、そのジャンルが要求されたジャンルと完全に一致するかどうかを確認します
- 一致した場合は、その本を
filteredResults配列に追加します filteredResultsをメインのresults配列に追加します
自分で試してみよう
// Initialize library data
const libraryData = {
books: [
{
id: 1,
title: "The Great Gatsby",
author: "F. Scott Fitzgerald",
year: 1925,
genre: "Fiction",
isRead: false,
rating: 0,
borrowed: false,
borrowedBy: "",
borrowDate: ""
}
],
readers: [
{
name: "John Smith",
favoriteGenre: "Fiction",
}
]
};
function manageLibrary(actions, data) {
let results = [];
for (let i = 0; i < actions.length; i++) {
const currentAction = actions[i];
const currentData = data[i];
switch (currentAction) {
case 'printBooks':
results.push(libraryData.books);
break;
case 'printReaders':
results.push(libraryData.readers);
break;
case "addBook":
// Add a new book to the library
let newBook = {
id: libraryData.books.length + 1,
title: currentData.title,
author: currentData.author,
year: currentData.year,
genre: currentData.genre,
isRead: false,
rating: 0,
borrowed: false,
borrowedBy: "",
borrowDate: ""
};
libraryData.books.push(newBook);
results.push("Book added successfully!");
break;
case "searchByTitle":
// Search for books by title
let searchResults = [];
for(let i = 0; i < libraryData.books.length; i++) {
if(libraryData.books[i].title.toLowerCase().includes(currentData.toLowerCase())) {
searchResults.push(libraryData.books[i]);
}
}
results.push(searchResults);
break;
default:
results.push("Invalid action!");
}
}
return results;
}論理とフローのすべてのレッスン
自分で練習してみよう: JavaScriptオンラインコンパイラ