2013-04-26 74 views
0

我有以下的功能,它只是通過對象的列表中運行並返回正確的:JavaScript函數「迴歸這」不工作

function findLine(textElement,caretIndex){ 
    jQuery.each(textElement.lines(), function() { 
     if(this.startIndex <= caretIndex && this.endIndex >= caretIndex) { 
      alert(this); 
      return this; 
     } 
    }); 
} 

當我用這個稱呼它我得到的回報undefined

line = findLine(textElement,caretIndex); 
alert(line); 

奇怪的是,當我運行line = findLine(textElement,caretIndex);函數內的警報被激發並返回正確的結果。所以this是正確的值,但是當功能外的第二個警報被解僱時,我得到undefined

當我從函數返回值或者將該值賦給變量時,發生錯誤。我在這裏做錯了什麼?

+0

你只能從返回交互功能,而不是主要功能。 – 2013-04-26 04:07:11

+0

這不是'每個'所做的。我想你在想'map'或'grep'。而且你沒有從'findLine'返回任何東西。 – Malvolio 2013-04-26 04:07:46

回答

1

從jQuery文檔上.each()

我們可以通過將回調函數返回false突破$。每()循環在特定的迭代。返回非錯誤與for循環中的continue語句相同;它會立即跳到下一個迭代。

所以你return this說法本質上是一種continue語句,因爲this是不假。改變你的功能,這可能工作(未經測試...而且有可能是更好的功能比。每次使用()如.filter()或.grep()):

function findLine(textElement,caretIndex){ 
    var result; 
    jQuery.each(textElement.lines(), function() { 
     if(this.startIndex <= caretIndex && this.endIndex >= caretIndex) { 
      alert(this); 
      result = this; 
      return false; // returning false in the callback just causes the loop to exit 
     } 
    }); 

    return result; 
} 
2

問題是,你是return thisjQuery.each方法的回調,並且你的findLine不返回任何東西。

function findLine(textElement,caretIndex){ 
    return jQuery.each(textElement.lines(), function() { 
     if(this.startIndex <= caretIndex && this.endIndex >= caretIndex) { 
      alert(this); 
      return this; 
     } 
    }); 
} 

如果returnjQuery.each叫你將與一個包含你想每個this一個jQuery對象告終。

+1

另外值得注意的是,如果您試圖減少數組中的項目,您可能確實想要[[jQuery.grep]](http://api.jquery.com/jQuery.grep/)調用 – 2013-04-26 04:09:28

+0

+ 1 - * findLine *不返回任何內容。 – RobG 2013-04-26 04:24:55