admin管理员组文章数量:1425161
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?
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?
-
Can you also add
emailString
value – Tushar Commented Nov 4, 2015 at 8:04 - 1 I don't understand how this question got two cowardly downvotes, yet the answer it evoked has two upvotes. – ProfK Commented Nov 9, 2015 at 6:28
1 Answer
Reset to default 8filter(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 = '[email protected];;;;[email protected];;;;[email protected];'
> str.split(/;+/)
< ["[email protected]", "[email protected]", "[email protected]", ""]
> str.split(/;+/).filter(Boolean)
< ["[email protected]", "[email protected]", "[email protected]"]
Here split
on this will return ["[email protected]", "[email protected]", "[email protected]", ""]
.
本文标签: javascriptWhat is the filter call for in this string split operationStack Overflow
版权声明:本文标题:javascript - What is the `filter` call for in this string split operation? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745398223a2656914.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论