javascript 无法获取未定义或空引用的属性“长度”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31875158/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 14:29:55  来源:igfitidea点击:

Unable to get property 'length' of undefined or null reference

javascriptjqueryregex

提问by GIVE-ME-CHICKEN

I have the following code - All it does it grabs the value in a text box, performs regex on the string and then counts how many asterisks are in the string value:

我有以下代码 - 它所做的一切都是在文本框中获取值,对字符串执行正则表达式,然后计算字符串值中有多少个星号:

var textBoxValue = $(textbox).val();

function countHowManyWildCards(stringToSearch) {

    var regex = new RegExp(/\*/g);
    var count = stringToSearch.toString().match(regex).length;
    return count;

}

if (countHowManyWildCards(textBoxValue) > 1) {

//Other code
}

The code seems to work, but there is an error appearing on:

代码似乎可以工作,但出现错误:

stringToSearch.toString().match(regex).length;

The error states:

错误指出:

Unable to get property 'length' of undefined or null reference

无法获取未定义或空引用的属性“长度”

But I am unclear why the code works, but I still have this error? Can someone fill me in on why this happening?

但我不清楚为什么代码有效,但我仍然有这个错误?有人可以告诉我为什么会发生这种情况吗?

回答by anubhava

Since matchis failing and not returning any array as a result calling .lengthon it will throw that error.

由于match失败并且不返回任何数组,因此调用.length它会抛出该错误。

To fix this you can use:

要解决此问题,您可以使用:

var count = (stringToSearch.match(regex) || []).length;

to take care of the case when matchfails. || []will return an empty array when match fails and [].lengthwill get you 0.

处理match失败时的情况。|| []匹配失败时将返回一个空数组,并[].length会得到你0

回答by GOTO 0

The return value of .match(regex)is nullif there are no matches.

.match(regex)的返回值是null如果没有匹配项。

回答by vinu

stringToSearch.toString().match(regex) will return null if stringToSearch does not contain any '*'

stringToSearch.toString().match(regex) 将返回 null 如果 stringToSearch 不包含任何 '*'