这是我教授的任务,制作披萨菜单: 每个馅料的比萨饼价格为10美元加额外费用: 奶酪:2美元;番茄1美元,蘑菇3美元,辣椒1美元
使用提示选择五个配件中的三个配件
使用for循环,如果测试计算披萨的总价
使用警报报告您的浇头和数组
使用其他提醒报告您的帐单和价格
我不明白的是如何使用' for循环'计算用户通过提示输入的所有浇头的价格
这是我到目前为止的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);
答案 0 :(得分:0)
您的解决方案几乎就在那里,因为您需要进行一些小的更改才能使代码正常工作:
var total[]
数组使用普通变量:var total
使用meow
数组而不是toppings
数组
(可选)您可以使用price
或toppings
数组作为内部
阵列
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);
&#13;
请注意我认为为内部和外部for循环设置不同的变量是一个好习惯:j
和i