Javascript:提示用户订购披萨配料,为配料分配价格并提醒总计?

Javascript: prompt user to order pizza toppings, assign price to toppings and alert total?

这是我教授的作业,制作披萨菜单: 披萨的价格为 10 美元,另加每种配料: 奶酪:2美元;西红柿 1 美元,蘑菇 3 美元,辣椒 1 美元

使用提示 select 将五个中的三个浇头放入数组中

使用 for 循环和 if 测试来计算披萨的总价

使用警报报告您的配料和阵列

使用另一个警报报告您的账单和价格

我不明白的是如何使用 'for loop' 计算用户通过提示输入的所有配料的价格

到目前为止,这是我的 js 代码:

var pizza = 10
var toppings = [];
var price = [];

var t1 = "cheese";
var p1 = 2;

var t2 = "tomato";
var p2 = 1;

var t3 = "mushrooms";
var p3 = 3;

var t4 = "peppers";
var p4 = 1;

toppings.push(t1);
toppings.push(t2);
toppings.push(t3);
toppings.push(t4);

price.push(p1);
price.push(p2);
price.push(p3);
price.push(p4);

var meow = [];
var m1 = prompt("Choose a desired topping: cheese, tomato, mushrooms, or peppers");
var m2 = prompt("Choose another desired topping: cheese, tomato, mushrooms, or peppers");
var m3 = prompt("Choose another desired topping: cheese, tomato, mushrooms, or peppers");

meow.push(m1);
meow.push(m2);
meow.push(m3);

var total = [];
var desired = [];

for (var i = 0; i < toppings.length; i++) {
   for (var i = 0; i < price.length; i++) {
       desired.push(toppings[i] + price[i]);
   }
}

total.push(desired + pizza);
alert(total);

您的解决方案就快完成了,因为您只需要做一些小的改动就可以让您的代码正常工作:

  1. 而不是使用 var total[] 数组使用普通变量:var total
  2. 对于外循环使用meow数组而不是toppings数组

  3. (可选)您可以使用 pricetoppings 数组作为内部 数组

var pizza = 10
var toppings = [];
var price = [];

var t1 = "cheese";
var p1 = 2;

var t2 = "tomato";
var p2 = 1;

var t3 = "mushrooms";
var p3 = 3;

var t4 = "peppers";
var p4 = 1;

toppings.push(t1);
toppings.push(t2);
toppings.push(t3);
toppings.push(t4);

price.push(p1);
price.push(p2);
price.push(p3);
price.push(p4);

var meow = [];
var m1 = prompt("Choose a desired topping: cheese, tomato, mushrooms, or peppers");
var m2 = prompt("Choose another desired topping: cheese, tomato, mushrooms, or peppers");
var m3 = prompt("Choose another desired topping: cheese, tomato, mushrooms, or peppers");

meow.push(m1);
meow.push(m2);
meow.push(m3);

var total = 0;
var desired = [];

for (var i = 0; i < meow.length; i++) {
    for (var j = 0; j < toppings.length; j++) {
        if (meow[i] == toppings[j]) 
            total = total + price[j];
    }
}

//total.push(desired + pizza);
alert("total " + total);

请注意,我认为为内部和外部 for 循环设置不同的变量是一个好习惯:ji