2014-02-21 60 views
0

我有Javascript這個簡單的問題,我想比較兩個變量,但它不能正常工作。我甚至檢查了變量的類型是相同的。請幫忙。 具體來說,我得到數字警報,我甚至得到當前計數器的警報是5總計是5,但我期望它進入「那麼」。變量比較

function fun(idCount, finalCallback) { 
this.idCount = parseInt(idCount); 
var counter = 0; 
var strings = {}; 
this.register = function(str, id) { 
    counter++; 
    strings[parseInt(id)] = str; 

    if(counter == this.idCount) { 
     alert("Going to override"); 
     //blabla 
    } else { 
     alert("Current counter is: " + counter + " Total " + idCount + ". Types: " + typeof counter + " and " + typeof idCount); 
    } 
} 
} 
+0

請記住,包括radix參數爲'parseInt':例如'parseInt(id,10)' –

+0

因爲無論如何它們都是數字,所以我相信我並不需要進行解析。但是怎麼可能數字顯然是相同的,但比較失敗了呢? – Tib51

回答

2

試試這個,

function fun(idCount, finalCallback) { 
    var self = this; 
    this.idCount = parseInt(idCount, 10); 
    var counter = 0; 
    var strings = {}; 
    this.register = function(str, id) { 
     counter++; 
     strings[parseInt(id, 10)] = str; 

     if(counter == self.idCount) { 
      alert("Going to override"); 
      //blabla 
     } else { 
      alert("Current counter is: " + counter + " Total " + idCount + ". Types: " + typeof counter + " and " + typeof idCount); 
     } 
    } 
} 
+0

使用自己做的伎倆。但你能解釋爲什麼嗎?我讀了什麼自我意味着(上下文切換),但如果我實際顯示變量,值似乎是相同的。那麼怎麼來? – Tib51

+0

在JavaScript中使用函數創建對象。所以如果你在任何函數裏面引用'this',它就是指這個函數本身。在你的情況下,如果你訪問函數this.register裏面的idCount,它會顯示值,但this.idCount不會。希望你清楚。 –

+0

謝謝!距離理解Javascript還有一步。啊,痛苦! :) – Tib51

0

只是指向,如果你使用==如果兩個對象都是同一類型或者沒有也沒關係。

實施例:

"0" == 0 // true 

要強制類型的比較,以及使用===

0 === 0 // true