Reputation: 5
I need some help with writing a loop. I'm still learning javascript and here is what i've done when manually creating the variables. As you can see I am basically creating three variables but because I dont know how to put this in a loop I have to manually declare each variable which is a pain as the input increases. For example this is really 4 items and there calories. If I wanted to do 20 items and there calories it would be a nightmare. what I would like to do is ask a if statement that ask's how many items did i eat today and the loop would then ask for the information below and stop when the if statement was satisfied.
var Food1 = window.prompt("What did you eat today?");
var Cal1 = window.prompt("How many calories was " + Food1);
var num1 = parseInt(Cal1);
var Food2 = window.prompt("What did you eat today?");
var Cal2 = window.prompt("How many calories was" + " " + Food2);
var num2 = parseInt(Cal2);
var Food3 = window.prompt("What did you eat today?");
var Cal3 = window.prompt("How many calories was " + Food3);
var num3 = parseInt(Cal3);
var Food4 = window.prompt("What did you eat today?");
var Cal4 = window.prompt("How many calories was" + " " + Food4);
var num4 = parseInt(Cal4);
Upvotes: 0
Views: 58
Reputation: 2576
var foods = []
var calories = []
var num_of_foods = window.prompt("How many foods did you eat today?");
for(var i=0; i<num_of_foods; i++){
var Food = window.prompt("What did you eat today?");
var Cal = window.prompt("How many calories was " + Food);
//Do whatever with Food and Cal
foods.push(Food)
calories.push(Cal)
}
Later when you need the collected values you can do:
for(var i=0; i<foods.length; i++){
food = foods[i]
calorie = calories[i]
//Use food and and calorie here
}
Upvotes: 2
Reputation: 11171
// prompt for number of foods
var n = parseInt(window.prompt("How many food items?"));
var food = [];
// we will loop through and ask n times
for (var i = 0; i < n; i++) {
// ask the user for the name of the food
var name = window.prompt("Enter name of food:");
// and ask how many calories said food item is
var calories = parseInt(window.prompt("How many calories was " + name + "?"));
// create an object to store the food's name and calories
var foodItem = {
name: name,
calories: calories
}
// push this to our array
food.push(foodItem);
}
// now, we can access our food items like this:
// food[0] will return the first food item in our array
// food[0].name will return the first item's name, e.g., "Chipotle Burrito"
// food[0].calories will return its calories, e.g., 9000
Upvotes: 2