Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to write a javascript function that counts to the number inputted

Tags:

javascript

Trying to take an integer and have it return as a
string with the integers from 1 to the number passed. Trying to use a loop to return the string but not sure how!

Example of how I want it to look:

count(5)    =>  1,  2,  3,  4,  5
count(3)    =>  1,  2,  3

Not really sure where to even start

like image 735
lessel132 Avatar asked Aug 05 '26 21:08

lessel132


2 Answers

I would do it with a recursive function. Keep concatenating the numbers until it reaches 1.

var sequence = function(num){
    if(num === 1) return '1';
    return sequence(num - 1) + ', ' + num;
}

Or just:

var sequence = (num) => num === 1 ? '1' : sequence(num - 1) + ', ' + num;
like image 106
MinusFour Avatar answered Aug 08 '26 10:08

MinusFour


You can use a for loop to iterate the number of times that you pass in. Then, you need an if-statement to handle the comma (since you don't want a comma at the end of the string).

function count(num) {
  var s = "";
  for(var i = 1; i <= num; i++) {
    s += i;

    if (i < (num)) {
      s += ', ';
    }
  }
  return s;
}

JSBin

like image 44
Jonathan.Brink Avatar answered Aug 08 '26 11:08

Jonathan.Brink



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!