繁体   English   中英

需要帮助来创建带有循环的if语句

[英]need help creating a if statement with a loop

我在编写循环时需要一些帮助。 我仍在学习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);
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 
}
// 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM