类型错误:无法读取 null 的属性“length”
2016-07-06
4483
我应该编写一个函数来从字符串中删除元音。我收到一条有关空值的错误消息。经过多次尝试修复后,消息仍然相同,但我尝试过滤空值。
TypeError: Cannot read property 'length' of null at getCount at Test.it at Test.describe at Object.exports.runInThisContext
function getCount(str) {
var vowelsCount = 0;
if (str && str.length){
vowelsCount=str.match(/[aeiou]/gi).length;
} else {
vowelsCount=0;
}
return vowelsCount;
}
describe("Case 1", function(){
it ("should be defined", function(){
Test.assertEquals(getCount("abracadabra"), 5)
});
});
1个回答
也许像这样?
function getCount(str) {
var vowelsCount = 0;
if (str && str.length){
var m = str.match(/[aeiou]/gi)
if (m) return m.length;
} else {
vowelsCount=0;
}
return vowelsCount;
}
describe("Case 1", function(){
it ("should be defined", function(){
Test.assertEquals(getCount("abracadabra"), 5)
});
});
river
2016-07-06