[英]I keep getting the error: TypeError: Cannot read property 'length' of null in Javascript
I have looked at the other threads.我看过其他线程。 I am a longtime lurker, this is the first time I'm posting (I think) or it's been a while.我是一个长期潜伏者,这是我第一次发帖(我认为)或者已经有一段时间了。 Anyways, I know what the problem is, I think, based on the other responses, it would seem that my variable isn't initialized.无论如何,我知道问题是什么,我认为,根据其他响应,我的变量似乎没有初始化。 But I don't think this is my issue.但我不认为这是我的问题。
I am trying to create a "Guess the word" game, similar to hangman without the stick figure.我正在尝试创建一个“猜词”游戏,类似于没有简笔画的刽子手。 I am creating a function that sees how many times the letter is in the word.我正在创建一个函数来查看字母在单词中出现的次数。 I'm not sure if I'm doing it right.我不确定我是否做得对。 Please look at my code and tell me what I'm doing wrong...?请查看我的代码并告诉我我做错了什么......?
Thank you!谢谢!
function timesInWord(word, letter) {
var re = new RegExp(letter,"gi");
var isMatch = word.match(re).length;
if (isMatch != null && isMatch > 0) {
return isMatch;
} else {
return "No Match, Try again!";
}
}
console.log(timesInWord("Mississippi","r"));
word.match(re)
will return null
if there are no matches.如果没有匹配项, word.match(re)
将返回null
。 That's the cause of the problem.这就是问题的原因。 If you want to check if there are matches, before getting the length of the array, check if it's not null
.如果要检查是否有匹配项,请在获取数组长度之前检查它是否不为null
。
When there is no match found word.match(re)
returns null
.当没有找到匹配时word.match(re)
返回null
。 Trying to call length
on null
causes the error.尝试在null
上调用length
会导致错误。
You do not need to use length
property.您不需要使用length
属性。 In your case only the null
checking is enough.在您的情况下,只有null
检查就足够了。 Try the following:请尝试以下操作:
function timesInWord(word, letter) { var re = new RegExp(letter,"gi"); var isMatch = word.match(re); if (isMatch != null) { return isMatch.length; } else { return "No Match, Try again!"; } } console.log(timesInWord("Mississippi","p"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.