Javascript 测试空长度属性为null并返回字符串的方法?
我正在处理一个挑战,并尝试设置它,以便在传递字符串时,可以确定该字符串中是否有2到4个字母参数 我对函数的测试成功了,但是如果匹配的数组长度为0(如果所述字符串中没有匹配的字母),则无法测量长度。我得到错误:Javascript 测试空长度属性为null并返回字符串的方法?,javascript,Javascript,我正在处理一个挑战,并尝试设置它,以便在传递字符串时,可以确定该字符串中是否有2到4个字母参数 我对函数的测试成功了,但是如果匹配的数组长度为0(如果所述字符串中没有匹配的字母),则无法测量长度。我得到错误:TypeError:无法读取null的属性“length” 我尝试使用一个条件,如果长度为null,它将返回一个字符串。不起作用,我不确定是否有办法将此错误转化为条件错误。有什么想法吗 TLDR:是否有方法捕获TypeError:在抛出错误之前无法读取null的属性“length” func
TypeError:无法读取null的属性“length”
我尝试使用一个条件,如果长度为null,它将返回一个字符串。不起作用,我不确定是否有办法将此错误转化为条件错误。有什么想法吗
TLDR:是否有方法捕获TypeError:在抛出错误之前无法读取null的属性“length”
function countLetters(string, letter) {
let regex = new RegExp(letter, 'g');
let matched = string.match(regex);
if (matched.length == null) {
return "There are no matching characters.";
} else {
let totalLetters = matched.length;
return (totalLetters >= 2 && totalLetters <= 4)? true : false;
}
}
您可以尝试let matched=string.match(regex)| |[]代码>
matched.length==null
,因此请尝试matched.length==0
如果(matched==null | | matched.length!=0)需要两个更改才能使其按需工作:
未找到匹配项时的句柄null
适当检查长度
更正代码如下:
function countLetters(string, letter) {
let regex = new RegExp(letter, 'g');
let matched = string.match(regex) || [];
if (matched.length == 0) {
return "There are no matching characters.";
} else {
let totalLetters = matched.length;
return (totalLetters >= 2 && totalLetters <= 4)? true : false;
}
}
函数countLetters(字符串、字母){
设regex=newregexp(字母“g”);
让matched=string.match(正则表达式)| |[];
if(matched.length==0){
return“没有匹配的字符。”;
}否则{
让Totaletters=匹配的长度;
return(totaletters>=2&&totaletters请注意string.match(regex)的规范,特别是:“如果没有匹配项,则返回null。”因此,您需要处理null响应。您无法避免这种情况。长度检查为零,而不是null。是的,match可以返回null(测试的前半部分),但如果返回值不是null(测试的第二部分)那么它是一个数组。数组的长度不能为null。好的调用实际上只是不加思考地复制了第二部分。谢谢你,在你的情况下,你只能检查匹配===null
,如果长度
为0
,就会发生这种情况。
countLetters('Letter', 'r');
false
countLetters('Letter', 'z');
//TypeError: Cannot read property 'length' of null
function countLetters(string, letter) {
let regex = new RegExp(letter, 'g');
let matched = string.match(regex) || [];
if (matched.length == 0) {
return "There are no matching characters.";
} else {
let totalLetters = matched.length;
return (totalLetters >= 2 && totalLetters <= 4)? true : false;
}
}