我知道有很多与此错误有关的问题,我已经检查了其中的大多数,没有人帮我解决了我的问题。 (这似乎很容易调试...)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