javascript - 我不断收到 NaN,但我不知道如何解决它

标签 javascript html nan

当到达 cost2 时就会发生这种情况。我认为问题可能在于尝试定义 price2,其他一切都正常。我是 JavaScript 新手,所以我确信这是一个简单的错误,但任何帮助都会很棒!

<html>
    <body>
        <h1>Gas Mileage</h1><br></br>
    </body>
    <script type="text/javascript">
        var mpg, price1, distance, gallons, cost1, price2, cost2;

        mpg = prompt("Enter your car's miles per gallon");
        document.write("Your car gets "+mpg+" miles per gallon.");
        document.write("<br>");

        price1 = prompt("Enter the current cost of gas");
        document.write("Gas currently costs $"+price1+" per gallon.");
        document.write("<br>");

        distance = prompt("Enter the amount of miles you would like to travel");
        gallons = distance/mpg;
        cost1 = gallons*price1;
        document.write("To travel "+distance+" miles, it will cost you $"+cost1);
        document.write("<br>");

        price2 = (0.1+price1);
        cost2 = gallons*price2;
        document.write("But if gas were to cost 10 cents more per gallon, it would cost you $"+cost2);

    </script>
</html>

最佳答案

prompt 始终返回一个字符串。

如果您想在计算中使用该输入,则必须使用 parseIntparseFloat:

var answer1 = parseInt(prompt("Question 1"));
var answer2 = parseFloat(prompt("Question 2"));

也就是说,除法和乘法运算符会将其参数强制转换为数字。

当此强制转换不起作用时,就会出现问题:price2 = (0.1+price1);
在那里,因为 + 只会将 2 个参数连接为字符串,所以 price2 可以是像 "0.11.54" 这样的字符串,如果 价格1“1.54”
尝试将任何数字与无效数字相乘会导致 NaN

将用户输入从字符串转换为数字可以解决该问题,因为 + 可以将两个数字加在一起,而不是连接它们。

关于javascript - 我不断收到 NaN,但我不知道如何解决它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32690593/

相关文章:

javascript - 用于在移动设备上触发日期输入的 HTML5 按钮

css - 不同版本的IE显示不同的颜色

arrays - 用 nan 替换缺失值

javascript - 为什么 JS 在 : ` + ' any_string'` 中返回 NaN

javascript - Mithril.js:如果 View 使用子组件,则排序数据不会重新呈现

javascript - DOM 帮助(显示水果的无序列表并给每个水果一个类)

javascript - 如何防止此ajax请求丢失数据

javascript - 无法使我的 Highcharts 以 Angular 5 响应

javascript - React.js 从数组创建多个表

javascript - 当答案超出数字范围或不是数字时执行