2014-02-21 62 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