我需要一些写一个循环的帮助。我还在学习javascript,这是我在手动创建变量时所做的。你可以看到我基本上创建了三个变量,但因为我不知道如何把它放在一个循环中我必须手动声明每个变量,这是一个痛苦随着输入的增加。例如,这实际上是4项和卡路里。如果我想做20件物品并且有卡路里,那将是一场噩梦。我想做的是问一个if语句,询问我今天吃了多少项,然后循环会询问下面的信息,并在if语句满足时停止。
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);
答案 0 :(得分:2)
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)
}
稍后当您需要收集的值时,您可以执行以下操作:
for(var i=0; i<foods.length; i++){
food = foods[i]
calorie = calories[i]
//Use food and and calorie here
}
答案 1 :(得分:2)
// 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