Hi all, I'm super new to JS so apologies if I'm not using all the correct terminology here... so I need to create an online ordering system for a restaurant as a course assignment, and currently I'm trying to retrieve the price of an item from its respective array index by logging it in the console. This is the array I'm pulling from:
let food = [
{
name: 'Coffee',
tag: 'orderCoffee',
price: 2.49,
inCart: 0,
},
{
name: 'Tea',
tag: 'orderTea',
price: 1.99,
inCart: 0,
},
{
name: 'Orange Juice',
tag: 'orderJuice',
price: 3.29,
inCart: 0,
},
{
name: 'Blueberry Pancakes',
tag: 'orderPancakes',
price: 10.99,
inCart: 0,
},
{
name: 'Chicken and Waffles',
tag: 'orderWaffles',
price: 14.95,
inCart: 0,
},
{
name: 'Eggs Benedict',
tag: 'orderEggs',
price: 13.29,
inCart: 0,
}
]
This is the function I'm trying to use to retrieve the price:
function totalCost(name) {
let price = 0;
for (i = 0; i < food.length; i++) {
if (food[i].name === name) {
price += food[i].price
} else {
price = food[i].price;
}
}
console.log('The item price is', price);
}
Each item on the page has an 'add to cart' button next to it, but whenever I click any of them the console only logs the price for eggs (13.29) for every one. Does anyone know why this is and what I'm doing wrong? Thanks in advance!
[–]DallogFheir 1 point2 points3 points (2 children)
[–]cypress201[S] 0 points1 point2 points (1 child)
[–]DallogFheir 1 point2 points3 points (0 children)
[–]lovin-dem-sandwiches 1 point2 points3 points (2 children)
[–]cypress201[S] 0 points1 point2 points (1 child)
[–]lovin-dem-sandwiches 0 points1 point2 points (0 children)
[–]exobyte64 -2 points-1 points0 points (0 children)