JavaScript的;下面两段代码有什么区别

时间:2017-10-09 15:14:37

标签: javascript

我试图理解这两段代码是如何不同的。

var bill=10.25+3.99+7.15;
var tip = bill*0.15;
var total=bill+tip;
total = total.toFixed(2);
console.log("$"+total);

var bill=10.25+3.99+7.15;
var tip = bill*0.15;
var total=bill+tip;
console.log("$"+total.toFixed(2));

1 个答案:

答案 0 :(得分:1)

评论中的解释:

   <script>
     var bill=10.25+3.99+7.15;
     var tip = bill*0.15; 
     var total=bill+tip; // total is number
     total = total.toFixed(2); // total has been converted into a string with only two decimal places
     console.log("$"+total); //prints out the '$' along with value of total variable which is a 'string'
     typeof total; //returns "string"
   </script>
    <script>
       var bill=10.25+3.99+7.15;
       var tip = bill*0.15;
       var total=bill+tip; //total is number
       console.log("$"+total.toFixed(2)); //even after this statement the type of 'total' is integer, as no changes were registered to 'total' variable.
       typeof total; //returns "number"
    </script>