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

查看:176
本文介绍了从数组中删除空字符串或空格字符串-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天全站免登陆