我试图理解这两段代码是如何不同的。
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));
答案 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>