简体   繁体   中英

Check variables and add them to comma separated list

I have 4 javascript variables:

a = 'first';
b = 'second';
c = 'third';
d = 'fourth';

What i want to achieve is to get them separated by comma, BUT. Sometimes where could be situations that some variables could be empty. Here is some of examples:

EXAMPLE1:

a = 'first';
b = '';
c = 'third';
d = '';

OUTPUT should be: first, third

EXAMPLE2:

a = '';
b = 'second';
c = '';
d = 'fourth';

OUTPUT should be: second, fourth

Maybe someone could help me to solve this?

Use .filter() as shown :-

a = '';
b = 'second';
c = '';
d = 'fourth';

var arr=[];
arr.push(a)
arr.push(b)
arr.push(c)
arr.push(d)
var newarr = arr.filter(function(value){
  return $.trim(value) != '' && value != null;
});
newarr = newarr.join(',');
alert(newarr);

Working Demo

The simpler solution (but not necessarily the more efficient) is :

var arr = [];
if (a) 
  arr.push(a);

if (b) 
  arr.push(b);

if (c) 
  arr.push(c);

if (d) 
  arr.push(d);

var commaSeparated = arr.join(',');

I like using an array for this kind of problem because you don't have to worry about append or not the commas to your result string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM