2015-12-21 66 views
-3

我有兩個變量,既包含文本和數字,我收到比較它們時錯誤的結果:比較包含文本數字

var x = "test_8" 
var y = "test_11" 
if(x > y){ 
    alert(x+" is greater than "+y); 
} 
else{ 
    alert(y+" is greater than or equal to "+x); 
} 

我得到警告說test_8大於test_11但我應該是得到其他警報。我猜我必須提取8和11作爲數字,但我不知道如何做到這一點。

+5

'8> 1',這就是發生 – Tushar

+1

如果你有「test_08」和「test_11」 – madox2

+0

不知道是否要關閉爲重複或沒有它的工作,但你在[Sort Array Elements(帶數字的字符串),自然排序](http://stackoverflow.com/q/15478954/1048572)中可以找到你的解決方案,它詳細描述了擬合比較函數 – Bergi

回答

1

需要將其轉換爲數字以進行精確比較。

function getNum(str) { 
 
     // it removes all non numeric, but regex can be differ according the str data which uses. 
 
     return Number(str.replace(/\D+/,"")); 
 
    } 
 

 
    var x = "test_8"; 
 
    var y = "test_11"; 
 

 
    if(getNum(x) > getNum(y)){ 
 
     alert(x+" greater than "+y); 
 
    } 
 
    else{ 
 
     alert(y+" greater than "+x); 
 
    }

+0

謝謝,這是我修復它的方式。我檢查變量是否有一個數字,如果有的話將其轉換爲數字 – NiallMitch14