简体   繁体   中英

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

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

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;

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

Try this:

function count(n) {
    var arr = [];
    for (var i = 1; i<=n; i++) {
        arr.push(i.toString());
    }
    return arr.toString();
}

这是一个非递归的解决方案:

var sequence = num => new Array(num).fill(0).map((e, i) => i + 1).toString();

here is a goofy way to do it

function count(i)
{
    while (i--) {
        out = (i + 1) + "," + this.out;
    }
    return (out + ((delete out) && "")).replace(",undefined", "");
}

Quite possibly the most ridiculous way, defining an iterator:

"use strict";

function count ( i ) {
  let n = 0;
  let I = {};
  I[Symbol.iterator] = function() {
     return { next: function() { return (n > i) ? {done:true}
                                                : {done:false, value:n++} } } };
  let s = "";
  let c = "";
  for ( let i of I ) {
      s += c + i;
      c = ", "
  }
  return s;
}


let s = count(3);
console.log(s);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM