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
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 ","
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

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);

Comments

0

Try it.

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

Comments

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

Comments

Your Answer

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.