Menu
Coddy logo textTech

Ver lista

Parte de la sección Fundamentos del Journey de JavaScript de Coddy. Lección 74 de 77.

challenge icon

Desafío

Fácil

Ahora, añade una función llamada viewList que no reciba argumentos e imprima la lista de la compra.

La función mostrará:

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

Para una lista con los siguientes elementos ["Milk", "Eggs", "Butter"].

Si la lista está vacía, muestra:

The grocery list is empty.

 

 

Añade el siguiente código al final de tu código para probarlo (en lugar del código de prueba anterior):

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

Pruébalo tú mismo

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

Todas las lecciones de Fundamentos

Practica por tu cuenta: Compilador de JavaScript online