繁体   English   中英

JS:仅针对非空和字符串值类型过滤数组

[英]JS: Filter array only for non-empty and type of string values

我试图过滤这样的数组:

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

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

我怎么做?

您可以检查字符串,并在过滤器方法中同时将其清空:

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

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

我应该提到“箭头”功能语法仅在支持ES6或更高版本的浏览器中有效。

替代方法是:

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

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

您可以使用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 !== '') ) 

> [1,,3,,5] .filter(String)
[1,3,5]

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

希望这可以帮助 :-)

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

const justStrings = array.filter(element => 
    (typeof element === 'string' || element instanceof String)
    && element
)

说明

为了确保您的元素是一个string您必须检查它不是变量类型let str = 'hello' )还是String实例new String('hello') ),因为这种情况将按typeof element返回object typeof element

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM