[英]JS: Filter array only for non-empty and type of string values
I am trying to filter an array like this: 我试图过滤这样的数组:
array.filter(e => { return e })
With this I want to filter all empty strings including undefined
and null
. 我想过滤所有空字符串,包括
undefined
和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.
因此,我还需要仅检查字符串值并删除所有其他值。
How do I do that? 我怎么做?
You could check for a string and empty both in your filter method: 您可以检查字符串,并在过滤器方法中同时将其清空:
array.filter(e => (typeof e === 'string') && !!e)
Note: !!e
returns false
if the element is null
, undefined
, ''
or 0. 注意:如果元素为
null
, undefined
, ''
或0,则!!e
返回false
。
I should mention that the "arrow"-function syntax only works in browsers that support ES6 or higher. 我应该提到“箭头”功能语法仅在支持ES6或更高版本的浏览器中有效。
The alternative is: 替代方法是:
array.filter(function(e) {
return (typeof e === 'string') && !!e;
});
Note: Keep in mind that Array.prototype.filter
doesn't exist in older browsers. 注意:请记住,在较旧的浏览器中不存在
Array.prototype.filter
。
You can check the type of the elements using typeof
: 您可以使用
typeof
检查元素的类型:
array.filter(e => typeof e === 'string' && e !== '')
Since ''
is falsy, you could simplify by just testing if e
was truthy, though the above is more explicit 由于
''
是虚假的,因此您可以通过测试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] .filter(String)
[1,3,5] [1,3,5]
When returning a method that consists of one line as a callback in es6 there is no need for return
as this happens implicitly. 在es6中返回包含一行内容的方法作为回调时,不需要
return
因为这是隐式发生的。
Hope this helps :-) 希望这可以帮助 :-)
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
)
To be shure your element is a string
you have to check that it isn't a variable type ( let str = 'hello'
) or an instance of String ( new String('hello')
) because this case would return object
by typeof element
. 为了确保您的元素是一个
string
您必须检查它不是变量类型 ( let str = 'hello'
)还是String的实例 ( new String('hello')
),因为这种情况将按typeof element
返回object
typeof element
。
Additionally you have to check if your element exists. 另外,您必须检查您的元素是否存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.