Javascript循环,总和和输出

时间:2011-10-20 20:52:36

标签: javascript

我正在尝试编写一个简单的javascript,或者我认为,使用“while”循环,“提示”和“警报”。 我希望用户提示询问他购买了多少件商品 然后我想取他输入的数字并返回相同数量的价格提示,然后我想用一个while循环来累计这些价格,并为整个事情增加7%的销售税,然后打印总额在警报窗口中

所以这就是我到目前为止所拥有的:

<html> <head> <title> Meal Total </title>
    <script language="JavaScript">
        var result;
        meal=prompt("Number of Items: ");
     </script> <script language = "JavaScript">
var tip = 1.07; </script>
</head> <body bgcolor = "white"> <center> <script language = "JavaScript">
if (meal> 0) {
    var index = 0;
    while (index < meal) {
        prompt("price of the item");
        index = meal;
    }
};
else if (meal == 0) {
    alert("Number is 0");
} else if (meal <0) {
    alert("You entered is negative");
} </script></center> </body></html>

正如您所看到的,我完成了大部分编码。我有它检测到负数或0表示输入的数字。我需要纠正下面的事情:首先,为什么它会忽略为输入值给出的提示数量?当我打开它并输入两个时,只显示1个提示窗口。其次,我如何总结提示框?

3 个答案:

答案 0 :(得分:0)

这是你要找的吗?

var items = 0, prices = [], tempPrice = 0;
while (isNaN(items) || items <= 0) {
    items = parseInt(prompt('How many meals?'), 10);
}
for (var i=1; i <= items; i++) {
    tempPrice = 0;
    while (isNaN(tempPrice) || tempPrice <= 0) {
        tempPrice = parseFloat(prompt('Price for meal ' + i + '?'));
    }
    prices.push(tempPrice);
}
alert('You ate ' + items + ' meals, their prices were ' + prices.join(","));

答案 1 :(得分:0)

};
else if (meal == 0) {

那是你的罪魁祸首。取出分号。你听起来像是一般的JavaScript或开发新手,所以这里有一个有用的提示,可以帮助你解决这个问题:在新窗口中打开Firefox错误控制台。那会让你明白你在那里遇到了语法错误。

答案 2 :(得分:0)

您应该稍微清理一下代码:

  • 缩进所有内容以使其更具可读性
  • 删除<center>bgcolor="white"部分,因为它们没有添加任何内容 - 您的<center>元素为空,默认情况下页面为白色,无论如何都不推荐使用bgcolor
  • 您的所有JavaScript代码应该只在一个块中,不需要其中的三个。此外,你应该将所有JavaScript放入头部而不是将其中的一部分混合到体内
  • 由于您在; }之后if,您的代码无法运行,但由于您说它部分有效,这可能不是问题所在。但请确保不要在;条款之后放置if

工作版本:http://jsfiddle.net/pimvdb/2dqSr/

var result = 0; // result is 0 at first
var meal   = +prompt("Number of Items: "); // convert into a number with +
var tip    = 1.07;

if (meal > 0) {
    var index = 0;
    while (index < meal) {
        var price = +prompt("price of the item");
        result = result + price; // add price to result
        index++; // increment index, so that while loop will stop after 'meal' times.
                 // If you set it to 'meal' directly, then 'index' will be equal to
                 // 'meal' after the first iteration, and the while loop will only
                 // run once (after the first iteration 'index < meal' is false).
    }
    alert(result * tip); // alert total price * tip

} else if (meal == 0) {
    alert("Number is 0");

} else if (meal < 0) {
    alert("You entered is negative");
}