admin管理员组文章数量:1368355
How can I use Array.join()
function with condition
For example:
var name = ['','aa','','','bb'];
var s = name.join(', ');
The output is: ', aa, , ,'bb',
I want to add a condition that will display only words that are not empty: "aa, bb"
How can I use Array.join()
function with condition
For example:
var name = ['','aa','','','bb'];
var s = name.join(', ');
The output is: ', aa, , ,'bb',
I want to add a condition that will display only words that are not empty: "aa, bb"
1 Answer
Reset to default 11You can use Array#filter
to remove empty elements from array and then use Array#join
on filtered array.
arr.filter(Boolean).join(', ');
Here, the callback function to filter
is Boolean constructor. This is same as
// ES5 equivalent
arr.filter(function(el) {
return Boolean(el);
}).join(', ');
As empty strings are falsy in JavaScript, Boolean('')
will return false
and the element will be skipped from the array. And the filtered array of non-empty strings is joined by the glue.
var arr = ['', 'aa', '', '', 'bb'];
var s = arr.filter(Boolean).join(', ');
console.log(s);
You can also use String#trim
to remove leading and trailing spaces from the string.
arr.filter(x => x.trim()).join(', ');
本文标签: javascriptArrayjoin() with conditionStack Overflow
版权声明:本文标题:javascript - Array.join() with condition - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743661104a2517962.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论