JavaScript NaN错误循环
JavaScript NaN error loop
运行此代码时收到NaN
错误。一段时间以来,我一直在努力找出原因,但一辈子都找不到。
为了澄清,我正在努力接受;
-
客户的欠款总额
-
有多少客户进入
function Summarise() { ID = prompt("Enter a Customer ID number ", -1) while(ID != -1) { var gasUsed = 0 var total = 0 gasUsed = prompt("Enter amount of gas used ", "0") ///Standard Rate is used to assist in the calculation of customers in excess of 60 Gas Used StandardRate = 60 * 1.75 if(gasUsed <= 60) { total= gasUsed * 2 document.write("Customers ID: " + ID) document.write(" has gas usage of " + gasUsed) document.write(" and owes $" + total) document.write("<br/>") } else { total= (gasUsed - 60) * 1.50 + StandardRate document.write("Customers ID: " + ID) document.write(" has gas usage of " + gasUsed) document.write(" and owes $" + total) document.write("<br/>") } var totalowed = total + totalowed var totalcustomers = ++totalcustomers ID = prompt("Enter a Customer ID number ", -1) } document.write("Total amount owed $" + totalowed) document.write("<br/>") document.write("Total Number of customers:" + totalcustomers) }
您需要在循环之前定义这两个变量:
var totalowed = 0;
var totalcustomers = 0;
当您为它们赋值时,它们最初是未定义的,这总是会产生问题。
你可以看到下面的工作片段:
function Summarise() {
ID = prompt("Enter a Customer ID number ", -1)
var totalowed = 0;
var totalcustomers = 0;
while(ID != -1)
{
var gasUsed = 0;
var total = 0;
gasUsed = prompt("Enter amount of gas used ", "0");
///Standard Rate is used to assist in the calculation of customers in excess of 60 Gas Used
StandardRate = 60 * 1.75
if(gasUsed <= 60)
{
total = gasUsed * 2;
document.write("Customers ID: " + ID);
document.write(" has gas usage of " + gasUsed);
document.write(" and owes $" + total);
document.write("<br/>");
}
else
{
total= (gasUsed - 60) * 1.50 + StandardRate;
document.write("Customers ID: " + ID);
document.write(" has gas usage of " + gasUsed);
document.write(" and owes $" + total);
document.write("<br/>");
}
totalowed = total + totalowed;
totalcustomers = ++totalcustomers;
ID = prompt("Enter a Customer ID number ", -1);
}
document.write("Total amount owed $" + totalowed);
document.write("<br/>")
document.write("Total Number of customers:" + totalcustomers);
}
Summarise();
totalowed和totalcustomers是在while循环中声明的,因此在它之外不可用。您需要在while环路之外定义它们。
您没有将提示中的字符串转换为整数。请参阅此处:
您可以使用:
ID = parseInt(prompt("Enter a Customer ID number ", -1), 10);
请记住为parseInt
函数提供基数值以确保其完整性。
如何从提示框中获取数值?
相关文章:
- RegEx导致无限循环/错误-请求的实体太大
- 循环错误的Javascript
- 对于循环错误:未捕获的引用错误,未定义变量.怎么了
- Jquery 循环错误
- wordpress循环中的循环错误
- 对无限循环错误进行故障排除
- 敲除循环错误 - 需要有关查找原因的建议
- Javascript 三元,带循环错误;“未捕获的语法错误:意外的令牌”
- 如何解决简化的JSON.stringify实现中的每个循环错误
- JQuery 脚本循环错误
- 无限循环错误
- 2D数组比较-嵌套循环错误
- JSON访问循环错误
- AngularJS承诺循环错误
- For循环错误,需要帮助解决
- Javascript无限循环错误在我的数组
- 样式表文件中的JS for循环错误
- For循环错误,For循环没有正确填充数组
- 在循环错误中将行添加到表中
- javascript循环错误