簡體   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