Javascript how to show each element of array on a new line
The for-loop is suspicious. Firstly, you do not process all items (the last one is missing, as @sarfraz pointed out). Sencondly you are returning the result (zzz
) in the for-loop body:
for (var i=0; i<=xxx; i++)
{
zzz[i] = zzz[i] + '<br />';
return zzz; // for-loop will stop here! resulting in ["value1<br />", "Value2", etc...]
}
In Javscript you can simple "join" the array:
return dates.split(',').join("<br />")
Since you are simply replacing strings you could use the replace
method:
return dates.replace(",", "<br />");
i have modified your function bit cleaner.since already stefan mentioned your mistake.
function splitDate(dates) {
if (dates != null)
{
var dates = dates.split(',');
var xxx = dates.length;
console.log(xxx);
for (var i=0; i<xxx; i++)
{
dates[i] = dates[i];
}
}
console.log(dates.join('\r\n'));
return dates.join('\r\n');
}
the above function you can do it in a single line:
if it's an array you can split into new line in following way:
var arr = ['apple','banana','mango'];
console.log(arr.join('\r\n'));
if it's a string:
var str = "apple,banana,mango";
console.log(str.split(',').join("\r\n"));