What is the `filter` call for in this string split operation?

孤者浪人 提交于 2019-12-25 17:16:08

问题


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

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

What could the filter(Boolean) part do?


回答1:


filter(Boolean) will only keep the truthy values in the array.

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.

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

Example

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"]

In the code

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

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"]

Here split on this will return ["a@b.com", "c@d.com", "dd@dd.com", ""].



来源:https://stackoverflow.com/questions/33516561/what-is-the-filter-call-for-in-this-string-split-operation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!