在过滤器Javascript中添加两个条件 [英] Add two conditions in filter Javascript

查看:78
本文介绍了在过滤器Javascript中添加两个条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Im trying to add two conditions in filter but only one works. The first condition check if it has empty spaces between words and the second condition if words.length is bigger than the given minimum length. if the string is "hello world" then i need to get when i split it ["hello", "world"]. Instead of that I am getting ["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为您提供了一个好的解决方案,请使用以下代码。

Seems like you want to filter if sumOfWord is not empty and its length is greater than minLength. @Barmar suggests you the good solution, use the following code.

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

这篇关于在过滤器Javascript中添加两个条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆