タイトルで検索
CoddyのJavaScriptジャーニー「論理とフロー」セクションの一部 — レッスン 44/65。
チャレンジ
簡単switch文の中に新しいケース searchByTitle を作成してください。このアクションは、本のタイトルで検索を行うものです。
searchByTitle ケースでは、以下の手順を行ってください:
currentDataパラメータは、検索する文字列です- 検索結果を格納するための空の配列
searchResultsを作成します - ライブラリ内のすべての本をループで確認します
- 各本について、そのタイトルに検索文字列が含まれているかチェックします
- 検索は、大文字と小文字を区別しないようにする必要があります(比較する前に両方の文字列を小文字に変換してください)
- 一致するものが見つかった場合は、その本を
searchResults配列に追加します searchResults配列をメインの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;
default:
results.push("Invalid action!");
}
}
return results;
}