2017-10-09 41 views
-4

我想了解这两段代码是如何不同的。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

他们没有任何实质性的意义。 – glennsl

+2

其中之一在输出之前更新'total'变量。另一个没有。 – David

+0

你为什么认为它们不同?它们都是一样的,就像'console.log(“$”+((10.25 + 3.99 + 7.15)* 1.15).toFixed(2));'。 – Xufox

回答

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>