简体   繁体   English

JavaScript中循环的最后一次迭代

[英]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: 您应该使用.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 ","

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 : 请注意,当您从数组开始时(这可能是您提出的问题背后的真正问题),有一个便捷的join函数:

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): 您应该检查是否已经到达循环的结尾(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 + ",");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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