Menu
CoddyTech

Xem danh sách

Thuộc phần Kiến thức cơ bản trong hành trình JavaScript của Coddy. Bài học 74 trên 77.

challenge icon

Thử thách

Dễ

Bây giờ, hãy thêm một hàm có tên viewList, không nhận đối số nào và in ra danh sách hàng tạp hóa.

Hàm sẽ in ra:

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

Với danh sách có các mục sau: ["Milk", "Eggs", "Butter"].

Nếu danh sách trống, hãy in ra:

The grocery list is empty.

 

 

Thêm đoạn code sau vào cuối code để kiểm tra hàm (thay cho code kiểm tra trước đó):

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

Tự làm thử

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

Tất cả bài học trong Kiến thức cơ bản

Tự luyện tập: Trình biên dịch JavaScript online