【发布时间】:2018-01-31 22:04:15
【问题描述】:
我正在为学校编写一个简单的程序,但遇到了一个问题,我希望有人可以帮助我
这些是赋值参数:
创建一个小的 JavaScript 程序:
- 创建一个值为 0 的变量“total”。
- 使用 do-while 循环 & 函数提示用户输入一系列数字或单词“quit” - quit 命令不区分大小写。
- 如果用户输入一个数字,请将新数字添加到运行总数中。
- 如果用户输入单词“退出”,循环应该停止执行。
- 如果用户输入了退出以外的其他单词,则提示消息应更改以让用户知道他们输入了无效的数据类型
- 退出循环时,显示一条消息,给出输入的总数
我的代码实现了所有的赋值参数,除了我不知道如何在输入退出命令后让提示消失。结果仍然显示在屏幕上,但提示不断循环。 这是我的代码:
var inputCounter = 0;
var total = 0;
newInput = null;
quit = /quit/i
function askForNum(a) {
do {
var newInput = prompt(a);
if (!newInput.match(quit)) {
if (newInput < "A" && newInput > "" ) {
var addThis = parseFloat(newInput);
}
if (isNaN(newInput)) {
askForNum("That wasn't a number! type \"quit\" to see the results!");
} else {
total += addThis;
inputCounter++;
askForNum("Every number you enter gets added together! type \"quit\" to see the results!");
}
}
} while (!newInput.match(quit)) {
document.getElementById("addition-script").innerHTML = "<b>TOTAL:</b> " + total + "<br><b># OF ENTRIES:</b> " + inputCounter;
return;
}
}
if (total == 0){
askForNum("initial: Every number you enter gets added together! type \"quit\" to see the results!");
}
【问题讨论】:
-
您正在使用两个独立的
newInputs。while条件检查全局条件,它仍然是null。尝试在函数外部声明所有变量,然后不要在内部重新声明它们,即不要再次使用var。 -
您正在使用递归(一个调用自身的函数)。在您的示例代码中,您需要输入与输入数字一样多次的 quit。
标签: javascript