2013-04-02 38 views
0

我有一個方法返回給定id模式的跨度數組。這個數組確實被創建,並且當我通過在函數結尾處打印出數組的值來測試時,所有正確的元素似乎都在其中。函數創建跨度數組總是返回未定義

這是函數:

function getAllSpansForID(sectionID) { 
    var foundAllSpans = false, 
     i = 1, 
     spanID, 
     span, 
     spanArray = new Array(); 

    /* Keep looking until we found all the selection spans.*/ 

    while (!foundAllSpans) { 
     spanID = sectionID + "-" + i; 
     span = document.getElementById(spanID); 

     /* 
     If we didn't get a span we can assume there are no more to find. 
     We are done with this loop. 
     */ 
     if (span == null) { 
      foundAllSpans = true; 
      console.log("Found all spans."); 
     } 

     /* 
     Else, add the span to the array we are going to return. 
     */ 
     else { 
      spanArray[i-1] = span; 
      i++; 
     } 
    } 

    console.log("returning spanArray.length: " + spanArray.length); 
    for (i = 0; i < spanArray.length; i++) { 
     console.log("spanArray[i].id: " + spanArray[i].id); 
     console.log("spanArray[i].outerHTML: " + spanArray[i].outerHTML); 
    } 

    return spanArray; 
} 

我的問題是,每當我調用該函數返回的值始終是不確定的。

此代碼:

var spansArray = getAllSpansForID(verseID), 
length = spansArray.length; 

總會產生這樣的錯誤:

Uncaught ReferenceError: spansArrray is not defined 

我發現有很多類似的問題對SO與returnign陣列由於劃定範圍的問題,但沒有符合我的確切情況。我試圖改變這種方法,包括使用spanArray.push(span)spanArray.push.apply(spanArray, span)添加我的跨度,但無濟於事。我沒有想法。

+3

爲什麼功能命名一次getAllSpansForID和另一個getAllSelectionSpansForVerse?那真的是一樣的嗎? –

+2

'spanArray!== spansArrray' – Andreas

+4

@Andreas它們在函數內部稱爲'spanArray',在外面稱'spansArray',所以應該沒問題。 – Xymostech

回答

1

在錯誤消息我能發現的r太多:

似乎又是錯字,而不是在你這裏張貼的代碼,但在你執行一個...

0

變化:

var spansArray = getAllSpansForID(verseID); 
var length = spansArray.length; 
+0

沒有區別。 – Bergi

+0

複製我的代碼並嘗試。應該有區別! –

+0

好的,那也可以解決OP的錯誤:-)但是他的問題沒有什麼功能上的差異。 – Bergi

0

D'OH!

你可以通過我的錯誤信息看,spansArrray(3 R的)是不確定的。我定義了spansArray(2個)。我修好了,一切正常。只是一個錯字....

我沒有舉起length = spansArray.length;直接從代碼,而只是寫出來,所以這裏發佈的代碼不會失敗。

對不起大家。我感謝所有的幫助一樣!