【发布时间】:2017-08-01 15:36:41
【问题描述】:
我正在尝试过滤这样的数组:
array.filter(e => { return e })
有了这个我想过滤所有空字符串,包括undefined和null。
不幸的是,我的数组有一些数组,它们不应该存在。所以我还需要只检查字符串值并删除所有其他值。
我该怎么做?
【问题讨论】:
标签: javascript arrays
我正在尝试过滤这样的数组:
array.filter(e => { return e })
有了这个我想过滤所有空字符串,包括undefined和null。
不幸的是,我的数组有一些数组,它们不应该存在。所以我还需要只检查字符串值并删除所有其他值。
我该怎么做?
【问题讨论】:
标签: javascript arrays
您可以使用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 可能会返回一个字符串,而不是过滤器回调定义所要求的布尔值。
const justStrings = array.filter(element =>
(typeof element === 'string' || element instanceof String)
&& element
)
要确保您的元素是 string,您必须检查它是否不是 变量类型 (let str = 'hello') 或 String 实例 ( new String('hello')) 因为这种情况下会通过typeof element 返回object。
此外,您必须检查您的元素是否存在。
【讨论】:
您可以在过滤器方法中检查字符串并清空:
array.filter(e => (typeof e === 'string') && !!e)
注意:如果元素是 null、undefined、'' 或 0,!!e 返回 false。
我应该提一下,“箭头”函数语法仅适用于支持 ES6 或更高版本的浏览器。
替代方案是:
array.filter(function(e) {
return (typeof e === 'string') && !!e;
});
注意:请记住,Array.prototype.filter 在旧版浏览器中不存在。
【讨论】:
当返回一个包含一行的方法作为 es6 中的回调时,不需要return,因为这是隐式发生的。
希望这会有所帮助:-)
let arr = ["", "", "fdsff", [], null, {}, undefined];
let filteredArr = arr.filter(item => (typeof item === "string" && !item) || !item)
console.log(filteredArr)
【讨论】: