简体   繁体   English

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

[英]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 . 我想过滤所有空字符串,包括undefinednull 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. 注意:如果元素为nullundefined''或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
)

Explanation 说明

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.

相关问题 如何在 typescript 中键入非空数组? - How to type a non-empty array in typescript? discord.js RangeError [MESSAGE_CONTENT_TYPE]: 消息内容必须是非空字符串 - discord.js RangeError [MESSAGE_CONTENT_TYPE]: Message content must be a non-empty string ESLint 7.1.0 错误:“模式”必须是非空字符串或非空字符串数组 - ESLint 7.1.0 Error: 'patterns' must be a non-empty string or an array of non-empty strings Firebase错误:提供给sendToDevice()的注册令牌必须是非空字符串或非空数组 - Firebase Error: Registration token(s) provided to sendToDevice() must be a non-empty string or a non-empty array 仅基于非空数组的字段匹配 - Match based on a field only with non-empty array 如何将非空值移到Javascript数组的开头 - How to move non-empty values to the front of a Javascript array RangeError [MESSAGE_CONTENT_TYPE]: 消息内容必须是非空字符串。 (discord.js v13) - RangeError [MESSAGE_CONTENT_TYPE]: Message content must be a non-empty string. (discord.js v13) Firebase Cloud Function错误:提供给sendToDevice()的注册令牌必须是非空字符串或非空数组 - Firebase Cloud Function error: Registration token(s) provided to sendToDevice() must be a non-empty string or a non-empty array 正则表达式仅在非空时匹配模式 - Regexp to match pattern only if non-empty Javascript:非空字符串的“真实”值 - Javascript: “truthy” values for non-empty strings
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM