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
-
1why dont you use javascript join() method w3schools.com/jsref/jsref_join.aspNishant Jani– Nishant Jani2013年03月28日 08:08:40 +00:00Commented Mar 28, 2013 at 8:08
6 Answers 6
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 ","
answered Mar 28, 2013 at 8:09
Derek 朕會功夫
94.8k45 gold badges199 silver badges255 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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:
answered Mar 28, 2013 at 8:06
Peter Rasmussen
17k8 gold badges50 silver badges64 bronze badges
Comments
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"
Comments
Try This-
str="";
for (var i=1; i<=10; i++) {
str=str+i + ",";
}
str.substr(0,str.length-1);
document.write(str);
answered Mar 28, 2013 at 8:07
Prateek Shukla
5952 gold badges9 silver badges28 bronze badges
Comments
Try it.
var arr = new Array();
for (i=1; i<=10; i++) {
arr.push(i);
}
var output = arr.join(',');
document.write(output);
Comments
for (var i=1; i<=10; i++) {
if (i == 10) {
document.write(i);
}
else {
document.write(i + ",");
}
}
Comments
lang-js