2013-11-22 75 views
-1

這裏是我執行的代碼:String對象的比較總是返回false

filterIssues: function(objectKey, text){ 
    var view = this; 
    var keys = objectKey.split("."); 
    var attributeKey = keys[0]; 
    var attributeName; 
    if (keys.length > 1){ 
     attributeName = keys[1]; 
    } 
    view.issues.each(function(issue){ 
     var value = issue.get(attributeKey); 
     console.log(text); 

     if (value === undefined || value === null){ 
      issue.trigger("hide"); 
      return; 
     } 

     if (attributeName !== undefined){ 
      value = value[attributeName]; 
     } 

     if(value !== undefined){ 
      var matchedText = value.substring(0, text.length - 1); 
      if (matchedText === text){ 
       issue.trigger("show"); 
       console.log(value); 
       return;  
      } 
     } 
     issue.trigger("hide"); 
    }); 
}  

matchedText == text總是返回false

這是我所得到的,當我玩的控制檯:

> matchedText 
"sande" 
> text 
"sande" 
> typeof(text) 
"string" 
> typeof(matchedText) 
"string" 
> matchedText === text 
false 
> matchedText == text 
false 

我也知道和===會經常檢查,如果兩個對象是相同的,我已閱讀 JavaScript equal operations anomaliesJavascript string equality

我忽略的代碼有什麼問題嗎?

+0

檢查'matchedText.length'和'text.length'。 –

+0

什麼樣的對象是'issues',什麼是'issues.each()'傳遞給函數(即什麼是'問題')? 'issue.get()'返回什麼? – RobG

+0

也許柵欄發佈錯誤? 'var matchedText = value.substring(0,text.length - 1);'你嘗試沒有 - 1? 'matchedText.valueOf()=== text.valueOf()'或者(==)會給你帶來什麼? – James

回答

0

那麼我最終發現了什麼問題。感謝您的回覆,我相信您可能沒有遇到缺乏信息的答案。

問題出在我傳遞給函數的text值上。 text最後包含"",這就是爲什麼比較不起作用。

+0

那麼你如何解決你的問題? – user3236289

0

我認爲你在濫用subString()方法。如果使用subString(),請使用不帶-1的長度。

+0

我改變了沒有-1的長度,仍然一樣。 – satran

+0

使用長度爲1是絕對錯誤的。子字符串的長度必須與真實的文本長度相同,不能小於1。 – bitfiddler

+0

那麼我改變了代碼使用切片而不是子字符串。仍然是同樣的問題。 – satran