Click here to Skip to main content
15,888,461 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
See more:
I've created a JS function called 'count' that accepts two integer parameters and returns a string containing all numbers between those two parameters. For example, if I called count(0,10) the program will display '0,1,2,3,4,5,6,7,8,9,10,'. However, I am trying to eliminate the comma after the 10 but am having no luck so far.
JavaScript
function count(num1, num2) 
{

  var strCou = '';
 
  for(var input1 = num1; input1 <= num2; input1++)
  {
    strCou += input1 + ", ";

  }
 
 console.log(strCou);
}
count(2,5);
Posted
Updated 11-Apr-13 6:55am
v2

Looking your original code, we can see that ", " is appended after each element. That's close, but not quite the way it works when writing a bunch of numbers on paper.

When we hand-write a list, we insert ", " before each element unless it's the first item.

So, an approach involves keeping track of the current element number. We then add ", " before each element except the first one.

JavaScript
function count(num1, num2)
{

  var strCou = '';
  var i = 0;
  for(var input1 = num1; input1 <= num2; input1++)
  {
    if (i != 0)
       strCou += ", ";

    strCou += input1;
    i++;
  }

 console.log(strCou);
}
count(2,5);
 
Share this answer
 
Try:
JavaScript
console.log(strCou.substring(0,strCou.length-1));

Using substring method will just give the needed string. Above, we removed the last character whatever it was.
 
Share this answer
 
JavaScript
function count(num1,num2) {
    var a=new Array();
    for(var i=num1;i<=num2;i++)
        a.push(i);
    return a.join(',');
}
console.log(count(0,10));
 
Share this answer
 
v2
This may be helpful to you or for any future readers on how to use the slice function properly JavaScript Substring: A Tale of Slicing and Dicing Strings[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900