gpt4 book ai didi

javascript - 类型错误 : Cannot read property 'length' of null

转载 作者:行者123 更新时间:2023-12-02 14:26:09 25 4
gpt4 key购买 nike

我应该编写一个从字符串中删除元音的函数。我收到有关空值的错误消息。经过多次尝试修复后,消息是相同的,但我尝试过滤空值。

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com