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
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.
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.
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.
TL;DR: use break to exit a loop in JavaScript.
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 ","
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With