7

I want to do something like this:

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

It shows a result like:

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

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

1,2,3,4,5,6,7,8,9,10
slhck
39.7k33 gold badges164 silver badges221 bronze badges
asked Mar 28, 2013 at 8:04
1

6 Answers 6

19

You should use .join instead:

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 ","
answered Mar 28, 2013 at 8:09
Sign up to request clarification or add additional context in comments.

Comments

5

You should check wether you have hit the end of the loop ( i == 10):

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

Here's a fiddle:

Fiddle

answered Mar 28, 2013 at 8:06

Comments

5

You might simply test when generating :

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

Note that when you start from an array, which might be your real question behind the one you ask, there is the convenient join function :

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

Comments

0

Try This-

str="";
for (var i=1; i<=10; i++) {
 str=str+i + ",";
}
str.substr(0,str.length-1);
document.write(str);
answered Mar 28, 2013 at 8:07

Comments

0

Try it.

 var arr = new Array();
 for (i=1; i<=10; i++) {
 arr.push(i);
 }
 var output = arr.join(',');
 document.write(output);
answered Mar 28, 2013 at 8:09

Comments

0
for (var i=1; i<=10; i++) {
 if (i == 10) {
 document.write(i);
 }
 else {
 document.write(i + ",");
 }
}
answered Mar 28, 2013 at 8:10

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.