问题
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