【问题标题】:JS: Filter array only for non-empty and type of string valuesJS:过滤数组仅用于非空和类型的字符串值
【发布时间】:2017-08-01 15:36:41
【问题描述】:

我正在尝试过滤这样的数组:

array.filter(e => { return e })

有了这个我想过滤所有空字符串,包括undefinednull。 不幸的是,我的数组有一些数组,它们不应该存在。所以我还需要只检查字符串值并删除所有其他值。

我该怎么做?

【问题讨论】:

    标签: javascript arrays


    【解决方案1】:

    您可以使用typeof检查元素的类型:

    array.filter(e => typeof e === 'string' && e !== '')
    

    由于'' 是假的,您可以通过测试e 是否为真来简化,尽管上面更明确

    array.filter(e => typeof e === 'string' && e)
    

    const array = [null, undefined, '', 'hello', '', 'world', 7, ['some', 'array'], null]
    
    console.log(
      array.filter(e => typeof e === 'string' && e !== '')
    )

    【讨论】:

    • 这也有效,但请记住,typeof e === 'string' && e 可能会返回一个字符串,而不是过滤器回调定义所要求的布尔值。
    • @cyrix,回调按值 that coerce to true (truthy) 过滤。我更喜欢隐含,它只是为了比较而提供的
    【解决方案2】:
    const justStrings = array.filter(element => 
        (typeof element === 'string' || element instanceof String)
        && element
    )
    

    说明

    要确保您的元素是 string,您必须检查它是否不是 变量类型 (let str = 'hello') 或 String 实例 ( new String('hello')) 因为这种情况下会通过typeof element 返回object

    此外,您必须检查您的元素是否存在。

    【讨论】:

      【解决方案3】:

      您可以在过滤器方法中检查字符串并清空:

      array.filter(e => (typeof e === 'string') && !!e)
      

      注意:如果元素是 nullundefined'' 或 0,!!e 返回 false

      我应该提一下,“箭头”函数语法仅适用于支持 ES6 或更高版本的浏览器。

      替代方案是:

      array.filter(function(e) {
          return (typeof e === 'string') && !!e;
      });
      

      注意:请记住,Array.prototype.filter 在旧版浏览器中不存在。

      【讨论】:

        【解决方案4】:

        当返回一个包含一行的方法作为 es6 中的回调时,不需要return,因为这是隐式发生的。

        希望这会有所帮助:-)

        let arr = ["", "", "fdsff", [], null, {}, undefined];
        
        let filteredArr = arr.filter(item => (typeof item === "string" && !item) || !item)
                          
        console.log(filteredArr)

        【讨论】:

          猜你喜欢
          • 2022-07-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-06-23
          • 2018-12-29
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多