在过滤器 Javascript 中添加两个条件



我试图在过滤器中添加两个条件,但只有一个有效。第一个条件检查单词之间是否有空格,第二个条件检查单词之间是否有空格,如果 words.length 大于给定的最小长度。 如果字符串"hello world"那么我需要在将其拆分["hello", "world"]时获取.取而代之的是我得到["hello", "", "", "", "world"]

let wordsLength = sumOfSentence.split(" ");    
let longWords = wordsLength.filter(function(sumOfWord){
    //check if the words length is bigger than the minimum length
    //check if it has extra empty spaces
    if(sumOfWord !== "") return sumOfWord.length >= minLength
});

似乎您想过滤 sumOfWord 是否为空并且其长度大于 minLength。 @Barmar建议你好的解决方案,请使用以下代码。

let wordsLength = sumOfSentence.split(" ");    
let longWords = wordsLength.filter(function(sumOfWord){
    return ((sumOfWord.trim() != '') && sumOfWord.length >= minLength)
});

最新更新