Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 278
Chathula Avatar asked Mar 28 '13 08:03

Chathula


People also ask

How do you find the last iteration in a for loop?

Use a counter variable and check when the counter value is zero then it is the first iteration and when the counter value is length-1 then it is the last iteration.

Why does JavaScript loop only use the last value?

Variable i Always Has The Last IndexBy the time the for loop reaches the last iteration, the i variable will end up holding the last index value. That's why the output will always be the last index, in my case, 5.

What are iterations in JavaScript?

Looping is when we want to run through the same block of code a specific number of times, or repeatedly until a condition is met. We specify this condition within the loop. Iteration occurs when we want to execute code once for each item in a collection, usually elements in an array or properties of an object.

How do you end a loop in node JS?

TL;DR: use break to exit a loop in JavaScript.


1 Answers

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 ","
like image 83
Derek 朕會功夫 Avatar answered Oct 10 '22 23:10

Derek 朕會功夫