목록 보기
Coddy JavaScript 여정의 기초 섹션에 포함된 레슨 — 77개 중 74번째.
챌린지
쉬움이제 인수를 받지 않고 식료품 목록을 출력하는 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");