具有条件的Array.join() [英] Array.join() with condition
问题描述
如何在条件下使用Array.join()
函数
例如:
var name = ['','aa','','','bb'];
var s = name.join(', ');
输出为:', aa, , ,'bb',
我想添加一个条件,该条件将仅显示不为空的单词:"aa, bb"
I want to add a condition that will display only words that are not empty: "aa, bb"
推荐答案
您可以使用 Array#join
.
You can use Array#filter
to remove empty elements from array and then use Array#join
on filtered array.
arr.filter(Boolean).join(', ');
在这里,filter
的回调函数是布尔构造函数.与
Here, the callback function to filter
is Boolean constructor. This is same as
// ES5 equivalent
arr.filter(function(el) {
return Boolean(el);
}).join(', ');
由于空字符串在JavaScript中是虚假的,因此Boolean('')
将返回false
,并且该元素将从数组中跳过.胶水将过滤后的非空字符串数组连接起来.
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);
您还可以使用 String#trim
从字符串中删除前导和尾随空格.
You can also use String#trim
to remove leading and trailing spaces from the string.
arr.filter(x => x.trim()).join(', ');
这篇关于具有条件的Array.join()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!