从数组中删除空字符串或空格字符串 - Javascript [英] Remove empty or whitespace strings from array - Javascript

查看:58
本文介绍了从数组中删除空字符串或空格字符串 - Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到了这个去除空字符串的漂亮方法 - arr = arr.filter(Boolean).

I've found this beautiful method for removing empty strings - arr = arr.filter(Boolean).

但它似乎不适用于空白字符串.

But it doesn't seem to work on whitespace strings.

var arr = ['Apple', '  ', 'Mango', '', 'Banana', ' ', 'Strawberry'];
arr = arr.filter(Boolean);
// ["Apple", "  ", "Mango", "Banana", " ", "Strawberry"]

// should be ["Apple", "Mango", "Banana", "Strawberry"]

是否有一种很好的方法可以将此方法扩展为删除空格,或者我应该先通过迭代数组来修剪空格?

Is there a nice way to expand this method to removing whitespaces as well or should i trim the whitespaces by iterating the array first?

推荐答案

filter 有效,但您需要正确的谓词函数,而 Boolean 不是(为此目的):

filter works, but you need the right predicate function, which Boolean isn't (for this purpose):

// Example 1 - Using String#trim (added in ES2015, needs polyfilling in outdated
// environments like IE)
arr = arr.filter(function(entry) { return entry.trim() != ''; });

// Example 2 - Using a regular expression instead of String#trim
arr = arr.filter(function(entry) { return /\S/.test(entry); });

(\S 表示一个非空白字符",所以 /\S/.test(...) 检查一个字符串是否至少包含一个非空白字符.)

(\S means "a non-whitespace character," so /\S/.test(...) checks if a string contains at least one non-whitespace char.)

或(可能有点过分且难以阅读)

or (perhaps a bit overboard and harder to read)

// Example 3
var rex = /\S/;
arr = arr.filter(rex.test.bind(rex));


使用 ES2015(又名 ES6)箭头函数,更加简洁:


With an ES2015 (aka ES6) arrow function, that's even more concise:

// Example 4
arr = arr.filter(entry => entry.trim() != '');

// Example 5
arr = arr.filter(entry => /\S/.test(entry));


现场示例 -- ES5 及更早的示例:


Live Examples -- The ES5 and earlier ones:

var arr = ['Apple', '  ', 'Mango', '', 'Banana', ' ', 'Strawberry'];
console.log("Example 1: " + JSON.stringify(arr.filter(function(entry) { return entry.trim() != ''; })));
console.log("Example 2: " + JSON.stringify(arr.filter(function(entry) { return /\S/.test(entry); })));
var rex = /\S/;
console.log("Example 3: " + JSON.stringify(arr.filter(rex.test.bind(rex))));

...以及 ES2015 (ES6) (如果您的浏览器尚不支持箭头功能,则无法使用):

...and the ES2015 (ES6) ones (won't work if your browser doesn't support arrow functions yet):

var arr = ['Apple', '  ', 'Mango', '', 'Banana', ' ', 'Strawberry'];
console.log("Example 4: " + JSON.stringify(arr.filter(entry => !entry.trim() == '')));
console.log("Example 5: " + JSON.stringify(arr.filter(entry => /\S/.test(entry))));

这篇关于从数组中删除空字符串或空格字符串 - Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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