2014-09-30 30 views
2

我正在JavaScript中做一個簡單的比較,但它不工作。 這裏是腳本爲什麼在JavaScript中「1.0」不等於「+1.0」?

var value = '1.0'; 
var minLimit = '+0.5'; 
var maxLimit = '+999'; 
if (value >= minLimit && value <= maxLimit) { 
    console.log(value); 
} 
else 
{ 
console.log('not matched'); 
} 

有什麼我缺少比較? 這裏是小提琴http://jsfiddle.net/9ouwkyyt/

+7

,因爲你正在做一個字符串比較 - http://jsfiddle.net/arunpjohny/9ouwkyyt/1/ – 2014-09-30 10:22:04

回答

7

這是因爲你正在做一個字符串比較,而不是數值比較。

值轉換爲數值 - 您可以使用一元加號,號()或者根據您的需要parseFloat()

var value = +'1.0'; 
 
var minLimit = +'+0.5'; 
 
var maxLimit = +'+999'; 
 
if (value >= minLimit && value <= maxLimit) { 
 
    console.log(value); 
 
} else { 
 
    console.log('not matched'); 
 
}

+0

了,所以我需要分析所有的值比較之前飄起..謝謝親愛的:-) – 2014-09-30 10:25:17

3

有+999之間」一個diffirence '和+999。

帶引號的那個是一個字符串,而沒有引號的是整數值。你想要做的是數字比較,而不是字符串比較。

0

您只比較字符串,因爲如果要以整數格式進行比較,請將結果轉換爲整數。

var value = '1.0'; 
    var minLimit = '+0.5'; 
    var maxLimit = '+999'; 
    if (parseInt(value)>= parseInt(minLimit) && parseInt(value)<= parseInt(maxLimit)) { 
     console.log(value); 
    } 
    else 
    { 
    console.log('not matched'); 
    } 
+0

添加一些解釋。現在你打到低質量隊列,因爲這只是代碼 – RickyA 2014-09-30 11:14:37

相關問題