此字符串拆分操作中的`filter`调用是什么? [英] What is the `filter` call for in this string split operation?

查看:72
本文介绍了此字符串拆分操作中的`filter`调用是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一行传统代码在分号上分割字符串:

I have a line of legacy code to split a string on semi-colons:

var adds = emailString.split(/;+/).filter(Boolean);

filter(Boolean)部分有什么用

推荐答案

filter(Boolean)只保留真实值

filter 期望通过提供 Boolean 作为参考,对于数组中的每个元素 e ,它将称为 Boolean(e) ,运算结果将返回到 filter

filter expects a callback function, by providing Boolean as reference, it'll be called as Boolean(e) for each element e in the array and the result of the operation will be returned to filter.

如果返回值是 true 元素 e 将保留在数组中,否则不包含在数组中。

If the returned value is true the element e will be kept in array, otherwise it is not included in the array.

示例

var arr = [0, 'A', true, false, 'tushar', '', undefined, null, 'Say My Name'];
arr = arr.filter(Boolean);
console.log(arr); // ["A", true, "tushar", "Say My Name"]

在代码中

var adds = emailString.split(/;+/).filter(Boolean);

我的猜测是字符串 emailString 包含值用; 分隔,其中分号可以多次出现。

My guess is that the string emailString contains values separated by ; where semicolon can appear multiple times.

> str = 'a@b.com;;;;c@d.com;;;;dd@dd.com;'
> str.split(/;+/)
< ["a@b.com", "c@d.com", "dd@dd.com", ""]

> str.split(/;+/).filter(Boolean)
< ["a@b.com", "c@d.com", "dd@dd.com"]

在此处分割会返回 [ a@b.com, c@d.com, dd @ dd .com,]

这篇关于此字符串拆分操作中的`filter`调用是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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