我有一個方法返回給定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)
添加我的跨度,但無濟於事。我沒有想法。
爲什麼功能命名一次getAllSpansForID和另一個getAllSelectionSpansForVerse?那真的是一樣的嗎? –
'spanArray!== spansArrray' – Andreas
@Andreas它們在函數內部稱爲'spanArray',在外面稱'spansArray',所以應該沒問題。 – Xymostech