2014-11-01 83 views
0

我被困在一個奇怪的情況下,從服務器接收到的JSON的一個數字屬性失敗了一個簡單的相等性測試數小時。Javascript比較數字從一個對象的屬性獲取作爲字符串

var form = {'answer':'','categoryDisplay':'dbAdmin','creationDate':null,'id':0,'question':'','techJobDisplay':null,'techJobId':65}; 

var selTechJobId = form.techJobId; 

var thisVal = String(65); 
var restoreVal = String(selTechJobId); 

alert("thisVal : " + thisVal + " | typeof thisVal : " + typeof thisVal); 
alert("restoreVal : " + restoreVal + " | typeof restoreVal : " + typeof restoreVal); 

alert("thisVal === restoreVal : " + thisVal === restoreVal); 

當我運行這個時,第三個警報顯示「false」。對我來說顯然應該顯示「真實」。我明顯錯過了一些東西。

我一直在Google上搜索幾個小時,我發現其中大部分都是關於類型不匹配的問題。正如你所看到的,我明確地將它們轉換爲String,所以它不應該成爲這裏的問題。

回答

2

使用:"thisVal === restoreVal : " + thisVal你concatening字符串,所以你與"65"

+0

Geez。餓的時候真的不好編碼。非常感謝!將在5分鐘後接受 – Bnrdo 2014-11-01 13:07:37

0

在你的變種比較"thisVal === restoreVal : 65"修正你的代碼

alert("thisVal === restoreVal : " + (thisVal === restoreVal)); 

因爲你比較 「」 thisVal === restoreVal:65"和 「65」 - 他們是不相等的

http://jsbin.com/dowihoqizi/1/

1

中出現的問題在你的代碼最後提醒您有+運營商這樣的後圓括號周圍的聲明 :

var form = {'answer':'','categoryDisplay':'dbAdmin','creationDate':null,'id':0,'question':'','techJobDisplay':null,'techJobId':65}; 

var selTechJobId = form.techJobId; 

var thisVal = String(65); 
var restoreVal = String(selTechJobId); 

alert("thisVal : " + thisVal + " | typeof thisVal : " + typeof thisVal); 
    alert("restoreVal : " + restoreVal + " | typeof restoreVal : " + typeof restoreVal); 



    alert("thisVal === restoreVal : " + (thisVal === restoreVal)); 

這樣,它不會嘗試 之前添加表達thisVal的第一部分的價值評估它

相關問題