JavaScript 中循环的最后一次迭代

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15676819/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 01:39:15  来源:igfitidea点击:

Last iteration of a loop in JavaScript

javascriptloopsfor-loop

提问by Chathula

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

采纳答案by Peter Rasmussen

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

小提琴

回答by u283863

You should use .joininstead:

你应该使用.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 ","

回答by Denys Séguret

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 joinfunction :

请注意,当您从数组开始时,这可能是您提出的真正问题,有一个方便的join功能:

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

回答by Prateek Shukla

Try This-

试试这个-

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

回答by Dieepak

Try it.

试试看。

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

回答by Daniel Chen

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