2011-12-29 17 views
0

我有一個計算器的代碼,現在我想添加一個%到結果,如果有一個結果。如果var不是NaN(所以它是一個數字)在jquery中添加%

當前的代碼是

var margins = num4.split(" "); 
    var topMarg = GetIntOrEmpty(margins[0]), 
     rightMarg = GetIntOrEmpty(margins[1]), 
     bottomMarg = GetIntOrEmpty(margins[2]), 
     leftMarg = GetIntOrEmpty(margins[3]); 
    console.log(topMarg, rightMarg, bottomMarg, leftMarg); 

    var shorthand1 = GetIntOrEmpty (topMarg); 
    shorthand1 += ' %'; 

如果shorthand1是空的,我希望它不添加「%」它和讓它空白。

任何想法?

+1

您需要向我們展示GetIntOrEmpty中的內容 – Mohsen 2011-12-29 20:27:18

+0

GetIntOrEmpty的代碼在哪裏? – 2011-12-29 20:27:24

+0

你有什麼問題? – 2011-12-29 20:27:44

回答

0
if (shorthand1 !== '') 
    shorthand1 += '%'; 
2

使用的if語句來檢查變量是否等於一個空字符串isNaN

if (shorthand1 !== '' && !isNaN(shorthand1)) { 
    shorthand1 += ' %'; 
} 

以上響應編輯的代碼通過Šime Vidas評論左,下方。

參考文獻:

+0

不適用於'0'。你想用'!=='。 – 2011-12-29 20:31:42

+0

啊?我沒有抓到;哎呀。所以可以推測:'shorthand1!=='''? – 2011-12-29 20:34:18

+0

是的。你只想使用'!='來比較哪種類型的強制顯式啓用(這是 - 從不)... – 2011-12-29 20:39:49

0

而不是測試爲空,您的GetIntorEmpty可能會返回'0'而不是空''。

需要沒有測試,爲0%是一樣的0

OR:

如果你要測試一個數字,是大於0需要的數量,然後另一種替代方案是:

if(shorthand >== 1) shorthand += '%'; 

'> == 1'只會在數字(大於0)上返回true。例如,它將在字符串'2'上返回false。

相關問題