为什么我的JavaScript循环不起作用?

时间:2013-10-28 01:19:06

标签: javascript

循环应该取每本书的价格,将其添加到总数中,然后将平均值放在每本书的页面上,直到用户输入“N”

<script type="text/javascript">
var ct = 1;
var yesORno = "Y";
while (yesORno = "Y"){
    book = prompt("What is the price of book #" + ct, 0);
    total = parseInt(book) + total;
    ans = total / ct;
    document.write("<p>With book #" + ct +" The average is " + ans + "</p>");
    ct = ct + 1;
    yesORno = prompt("Would you like to continue? (Y/N)", "")
}
</script>

3 个答案:

答案 0 :(得分:8)

您应该将while条件更改为:

while (yesORno == "Y")

仅使用=会将“Y”值分配给yesORno并返回自身,该值将被评估为true并使其永久运行。

答案 1 :(得分:3)

var ct = 1;
var yesORno = "Y";
while (yesORno == "Y"){
    book = prompt("What is the price of book #" + ct, 0);
    total = parseInt(book) + total;
    ans = total / ct;
    document.write("<p>With book #" + ct +" The average is " + ans + "</p>");
    ct = ct + 1;
    yesORno = prompt("Would you like to continue? (Y/N)", "")
}

看第三行。

答案 2 :(得分:3)

与其他人一样,您使用了赋值运算符=而不是等于运算符==或严格相等运算符===

但是,您也可以使用do while循环重构代码。这样就无需使用yesORno变量。

do {
    //...
} while(prompt("Would you like to continue? (Y/N)", "") === 'Y')
相关问题