![](/img/trans.png)
[英]Why is javascript treating in function (local) variables as global (window) variables?
[英]Javascript is treating variables as Strings, why?
我有變量 y,它是一個小計。 它的值根據 html 發生的情況而有所不同,但在整個腳本中我是這樣聲明的:
var y = 21.78;
等等。為什么在我最后一個計算總和的方程式中,當我想添加值時,它會將它們視為字符串?
var tax = (0.055*y).toFixed(2);
var totalprice = y+tax;
/* totalprice holds "21.781.20" instead of 22.98 */
根據:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number/toFixed
toFixed()
返回:
數字的字符串表示形式,不使用指數表示法且小數點后有 digits 數字。
因此, y+tax
被轉換為一個字符串,因為其中一個操作數是一個字符串。
在我看來,這是有道理的,因為 Javascript 的固有數字類型無法存儲特定數量的小數位數字,因此字符串將是最合適的數據結構來存儲它。
我建議您在調用toFixed()
之前完成所有添加,因為該方法最適合格式化顯示 output。
var taxRate = 0.055; var subtotal = 21.78; var tax = (taxRate * subtotal).toFixed(2), totalprice = ((1+taxRate) * subtotal).toFixed(2); document.write(totalprice);
.toFixed() 方法返回一個字符串。 嘗試將該方法應用為所有其他計算之后的最后一步。
這是一個簡單的修復。 將“+”放在稅收變量前面,將其轉換為數字。
var y = 21.78;
var tax = (0.055*y).toFixed(2);
var totalprice = y+ (+tax);
totalprice === 22.98;
如果您在使用 toFixed 時不希望出現任何舍入錯誤,請在您的腳本中包含它的重新實現。 http://bateru.com/news/2012/03/reimplementation-of-number-prototype-tofixed/
根據我的經驗,如果有任何機會,Javascript 會將“+”符號視為連接而不是加法。 它不止一次讓我抓狂。 我通常會這樣做而不是偶然串聯:
var totalprice = parseInt(y)+parseInt(tax);
當字母替換值時,當您需要+
時乘以1
。
var totalprice = (y*1) + tax .
其他操作數工作正常,只是+
操作數在變量替換值時需要特殊處理。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.