Menu
Coddy logo textTech

リストの表示

CoddyのJavaScriptジャーニー「基礎」セクションの一部 — レッスン 74/77。

challenge icon

チャレンジ

簡単

次に、引数を受け取らず、食料品リストを表示するviewListという名前の関数を追加してください。

この関数は以下のように出力します:

Grocery List:
1. Milk
2. Eggs
3. Butter

これは、["Milk", "Eggs", "Butter"]というアイテムが含まれるリストの場合の例です。

リストが空の場合は、以下を出力してください:

The grocery list is empty.

 

 

コードの最後に以下のコードを追加してテストしてください(以前のテストコードの代わりに使用します):

viewList();
addItem("Milk");
addItem("Bread");
addItem("Eggs");
viewList();
removeItem("Bread");
viewList();
removeItem("Cheese");

自分で試してみよう

// Grocery list array
let groceryList = [];

// Function to add an item to the grocery list
function addItem(item) {
	groceryList.push(item);
	console.log(`${item} added to the grocery list.`);
}

// Function to remove an item from the grocery list
function removeItem(item) {
	const index = groceryList.indexOf(item);
	if (index !== -1) {
		groceryList.splice(index, 1);
		console.log(`${item} removed from the grocery list.`);
	} else {
		console.log(`${item} is not in the grocery list.`);
	}
}

addItem("Milk");
addItem("Bread");
addItem("Eggs");
removeItem("Bread");
removeItem("Cheese");

基礎のすべてのレッスン