Javascript how to show each element of an array on a new line

I have a string string form, separated by commas. I use split to get each value, and after that I want to show every value in a new line, but what really happens is that I get every value in a new line, except for the last two, which are shown together on the same line. Just to make it clear:

value1

value2

value3

value4, value5

Here is the function I'm using:

 _checkDates: function(dates) { if (dates != null) { var zzz = dates.split(','); var xxx = zzz.length; console.log(xxx); for (var i=0; i<=xxx; i++) { zzz[i] = zzz[i] + '<br />'; return zzz; } } return dates; } 

Just to be clear, this is written in ExtJS 4, I'm pretty sure that in this case the problem is pure JavaScript and not related to ExtJS 4, but in any case, maybe I'm wrong.

So, any ideas why this is happening, and how could I make this last element also available on a new line?

thanks

Leron

+13
source share
3 answers

The downhole cycle is suspicious. Firstly, you are not processing all elements (the latter is missing, as @sarfraz pointed out). Sencondly, you return the result ( zzz ) to 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 simply "attach" an array:

 return dates.split(',').join("<br />") 

Since you just replace the strings, you can use the replace method:

 return dates.replace(",", "<br />"); 
+11
source

I changed your bit cleaner. Since stefan already 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 one line:

if the array can be split into a new line as follows:

 var arr = ['apple','banana','mango']; console.log(arr.join('\r\n')); 

if this is a line:

 var str = "apple,banana,mango"; console.log(str.split(',').join("\r\n")); 
+22
source

For React-Native

 const your_array_name = [ { id: 1, text: 'Lorem ipsum is simple dummy text for printing the line', skills: ['javascript', 'java'] }, { id: 2, text: 'Lorem ipsum is simple dummy text.', skills: ['javascript', 'java'] } ] 

<Text style={{color:'#ff8500',fontSize:18}}>{your_array_name.skills.splice(',').join("\n")}</Text>

0
source

All Articles