繁体   English   中英

为什么我的涉及if语句的JavaScript计算不起作用?

[英]Why won't my JavaScript calculations involving if statements work?

这个想法是产生一个从1到10的随机数,这将是订购产品的磅数。 然后,使用该数字,代码将计算产品成本和运输成本,并将它们加在一起以创建总计。 然后它将有关购买的信息写入HTML文档。

问题不在于随机数生成器; 很好 这似乎也不是将信息写入文档的最后一步。 相反,似乎包含在if-else语句中的我的计算不起作用。 JavaScript正在读取costBoxcostShippingcostTotal为未定义。 我尝试过更改语法,并且遍历了代码以确保不丢失括号或方括号。 我已经查阅了我的教科书,但是其中的代码也是如此。 您能帮我找出问题所在吗?

这是我的代码:

var num = Math.ceil(Math.random() * 10);
       var costBox;
       var costShipping;
       var costTotal;

       if (num >= 1 && num <= 5) {
        costBox == 20;
       }
       else if (num >= 6 && num <= 9) {
        costBox == 15;
       }
       else if (num == 10) {
        costBox == 10;
       }

       if (num >= 1 && num <= 3) {
        costShipping == 5;
       }
       else if (num >= 4 && num <= 7) {
        costShipping == 10;
       }
       else if (num == 8 || num == 9) {
        costShipping == 15;
       }
       else if (num == 10) {
        costShipping == 20;
       }

       costBox == costBox * num;
       costTotal == costBox + costShipping; 

       window.onload = function() {
        document.getElementById("pageNum").innerHTML = num;
        document.getElementById("pageBox").innerHTML = costBox.toFixed(2);
        document.getElementById("pageShipping").innerHTML = costShipping.toFixed(2);
        document.getElementById("pageTotal").innerHTML = costTotal.toFixed(2);
       }

以下是NPE建议后的代码:

       var num = Math.ceil(Math.random() * 10);
       var costBox;
       var costShipping;
       var costTotal;

       if (num >= 1 && num <= 5) {
        costBox = 20;
       }
       else if (num >= 6 && num <= 9) {
        costBox = 15;
       }
       else if (num == 10) {
        costBox = 10;
       }

       if (num >= 1 && num <= 3) {
        costShipping = 5;
       }
       else if (num >= 4 && num <= 7) {
        costShipping = 10;
       }
       else if (num = 8 || num = 9) {
        costShipping = 15;
       }
       else if (num = 10) {
        costShipping = 20;
       }

       costBox == costBox * num;
       costTotal == costBox + costShipping; 


       window.onload = function() {
        document.getElementById("pageNum").innerHTML = num;
        document.getElementById("pageBox").innerHTML = costBox.toFixed(2);
        document.getElementById("pageShipping").innerHTML = costShipping.toFixed(2);
        document.getElementById("pageTotal").innerHTML = costTotal.toFixed(2);
       }

以下是比较,而不是分配:

    costBox == 20;

==更改为= (在此以及在所有其他类似的地方)。

另请注意,允许Math.random()返回正好为0 ,并且您的代码未对其进行处理。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM