So che ci sono un sacco di domande relative a questo errore e ho controllato la maggior parte di loro e nessuno mi aiuta a risolvere il mio problema. (Che sembra così facile da mettere a punto ...)Javascript Uncaught TypeError: Impossibile leggere la proprietà '0' di undefined
Ho un array (che è vuoto AAT prima):
var words = [];
E la mia funzione hasLetter, controlla se troviamo una lettera (oggetto) in array (che chiamo qui: d) words.
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; }
e ho una funzione chiamata addLetter che controlla se hasLetter restituisce true/false e quindi crea o no di conseguenza un nuovo nodo.
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);
}
e se provo:
addLetter("a",words);
restituisce:
Uncaught TypeError: Cannot read property '0' of undefined
non so cosa fare per dire "se è indefinita allora don guardate dentro o qualcosa del genere ...
Grazie
Se si desidera trovare una lettera in serie, quindi (words.indexOf (lettera)> 0) restituirà se la lettera è presente o meno. – mohamedrias
Non è possibile eseguire 'hasLetter (" a ", words []);', dovrebbe essere 'hasLetter (" a ", words);' – theonlygusti
@ mohamedrias no non lo farà. – theonlygusti