我应该编写一个从字符串中删除元音的函数。我收到有关空值的错误消息。经过多次尝试修复后,消息是相同的,但我尝试过滤空值。
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)
});
});
最佳答案
也许像这样?
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)
});
});
关于javascript - 类型错误 : Cannot read property 'length' of null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38221016/