JS:仅针对非空和字符串值类型过滤数组 [英] JS: Filter array only for non-empty and type of string values

查看:51
本文介绍了JS:仅针对非空和字符串值类型过滤数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to filter an array like this:

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

为此,我想过滤所有空字符串,包括 undefined null .不幸的是我的数组有一些数组,这些数组不应该存在.因此,我还需要仅检查字符串值并删除所有其他值.

With this I want to filter all empty strings including undefined and null. Unfortunately my array have some arrays, which should not be there. So I need also to check only for string values and remove all other.

我该怎么做?

推荐答案

您可以使用

You can check the type of the elements using typeof:

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

由于''是虚假的,因此您可以通过测试 e 是否真实来简化,尽管上述内容更为明确

Since '' is falsy, you could simplify by just testing if e was truthy, though the above is more explicit

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 !== '')
)

这篇关于JS:仅针对非空和字符串值类型过滤数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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