Last loop iteration in JavaScript

I want to do something like this:

for (var i=1; i<=10; i++) { document.write(i + ","); } 

The result is displayed:

 1,2,3,4,5,6,7,8,9,10, 

But I want to remove the last ",", and the result should look like this:

 1,2,3,4,5,6,7,8,9,10 
+7
source share
6 answers

You should check if you are at the end of the loop (i == 10):

 for (var i=1; i<=10; i++) { document.write(i + (i==10 ? '': ',')); } 

Here's the fiddle:

Fiddle

+4
source

Instead, use .join :

 var txt = []; //create an empty array for (var i = 1; i <= 10; i++) { txt.push(i); //push values into array } console.log(txt.join(",")); //join all the value with "," 
+19
source

You can simply test when creating:

 for (var i=1; i<=10; i++) { document.write(i); if (i<9) document.write(','); } 

Note that when you start with an array, which may be your real question for the one you are asking, there is a convenient join function:

 var arr = [1, 2, 3]; document.write(arr.join(',')); // writes "1,2,3" 
+5
source

Try it -

 str=""; for (var i=1; i<=10; i++) { str=str+i + ","; } str.substr(0,str.length-1); document.write(str); 
0
source

Give it a try.

  var arr = new Array(); for (i=1; i<=10; i++) { arr.push(i); } var output = arr.join(','); document.write(output); 
0
source
 for (var i=1; i<=10; i++) { if (i == 10) { document.write(i); } else { document.write(i + ","); } } 
0
source

All Articles