我知道有很多與此錯誤有關的問題,我已經檢查了其中的大多數,沒有人幫我解決了我的問題。 (這似乎很容易調試...)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
我不知道該怎麼辦說「如果它是不確定的,然後不要不要看着它或沿着這些線......
個感謝
如果你想在數組中找到一個字母,那麼(words.indexOf(letter)> 0)會返回你是否存在該字母。 – mohamedrias 2015-04-03 11:28:21
你不能做'hasLetter(「a」,單詞[]);',應該是'hasLetter(「a」,words);' – theonlygusti 2015-04-03 11:28:29
@mohamedrias不會。 – theonlygusti 2015-04-03 11:28:46