JavaScript NaN错误循环

JavaScript NaN error loop

本文关键字:循环 错误 NaN JavaScript      更新时间:2023-09-26

运行此代码时收到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函数提供基数值以确保其完整性。

如何从提示框中获取数值?