8

我知道有很多與此錯誤有關的問題,我已經檢查了其中的大多數,沒有人幫我解決了我的問題。 (這似乎很容易調試...)Javascript未捕獲TypeError:無法讀取屬性'0'的undefined

我有一個數組(裏面是空的AAT在前):

var words = []; 

我的功能hasLetter,檢查,如果發現了一個字母(對象)數組(我稱之爲:d)單詞。

function hasLetter(letter,d){ 

// if words[0] not null should return object of letter "a", here we getting 
// the index of the letter (since ascii of "a" is 97, I substract 97) 
var ascii = letter.charCodeAt(0)-97; 

//Trying to not get an error with this but still creates an err 
if(typeof d[ascii ] !== "undefined" && d[ascii ] !== null && d[ascii ].length > 0){ 
    if(d[ascii].letter == letter){ 
     return true; 
    } 
} 
return false; } 

,我有一個名爲addLetter功能用來檢查是否hasLetter返回true/false,然後創建或沒有相應的新節點。

function addLetter(letter,d){ 
var ascii = letter.charCodeAt(0)-97; 
if(!hasLetter(letter,d)){ 
    document.write("This letter" + letter + " hasn't been found in words."); 
    d[ascii] = new Node(letter); 
} 
    document.write("This letter " + letter + " already exists in words."); 
    document.write(d[ascii].letter); 

}

,如果我測試:

addLetter("a",words); 

返回:

Uncaught TypeError: Cannot read property '0' of undefined 

我不知道該怎麼辦說「如果它是不確定的,然後不要不要看着它或沿着這些線......

感謝

+0

如果你想在數組中找到一個字母,那麼(words.indexOf(letter)> 0)會返回你是否存在該字母。 – mohamedrias 2015-04-03 11:28:21

+0

你不能做'hasLetter(「a」,單詞[]);',應該是'hasLetter(「a」,words);' – theonlygusti 2015-04-03 11:28:29

+0

@mohamedrias不會。 – theonlygusti 2015-04-03 11:28:46

回答

9

的錯誤是在這裏:

hasLetter("a",words[]); 

您正在傳遞words的第一項,而不是數組。

相反,陣列傳遞給函數:

hasLetter("a",words); 

問題解決了!


這裏的問題是什麼故障:

我在你的瀏覽器猜測(鉻拋出一個不同的錯誤),words[] == words[0],所以當你打電話hasLetter("a",words[]);,你實際上調用hasLetter("a",words[0]);。所以,從本質上講,你將第一項單詞傳遞給你的函數,而不是這個數組作爲一個整體。

當然,因爲words只是一個空數組,words[0]undefined。因此,你的函數調用居然是:

hasLetter("a", undefined); 

這意味着,當您嘗試訪問d[ascii],你實際上是試圖訪問undefined[0],因此錯誤。

+0

是的,我沒有通過添加「[]」我的呼叫hasLetter失敗,但我的錯誤實際上來自另一個函數(它來自這一個,但調用另一個)。我會創建一個新的線程(或者我應該更新這個?),但感謝解釋這個,它幫助:) – 2015-04-03 13:25:58

+0

好吧,是的,這是有道理的;我對你遇到的錯誤感到困惑,我預料它會更多地沿着「意想不到的」方向發展。「不管怎樣,謝謝!如果你給這個答案投票,我會有2k的複製! – theonlygusti 2015-04-03 14:09:04

2

有,當我用你的代碼沒有錯誤,

但我調用hasLetter方法是這樣的:

hasLetter("a",words); 
0

我不認爲你需要在你的函數調用中使用[]hasLetter("a",words);的輸出是什麼?

相關問題