简体   繁体   中英

Last iteration of a loop in JavaScript

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

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

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"

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

Try This-

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

Try it.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM