查看清单
本课属于 Coddy JavaScript 学习旅程的“基础知识”单元。第 74 课,共 77 课。
挑战
简单现在,添加一个名为 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");基础知识中的所有课
自己练习: JavaScript 在线编译器