Javascript for loop console print in one line

前端 未结 6 1952
时光取名叫无心
时光取名叫无心 2020-12-29 14:02

I\'m trying to get the output from my for loop to print in a single line in the console.

for(var i = 1; i < 11; i += 1) {
    console.log(i);
}

相关标签:
6条回答
  • 2020-12-29 14:19

    No problem, just concatenate them together to one line:

    var result  = '';
    for(var i = 1; i < 11; i += 1) {
      result = result + i;
    }
    console.log(result)

    or better,

    console.log(Array.apply(null, {length: 10}).map(function(el, index){
       return index;
    }).join(' '));

    Keep going and learn the things! Good luck!

    0 讨论(0)
  • 2020-12-29 14:19
    // 1 to n
    const n = 10;
    
    // create new array with numbers 0 to n
    // remove skip first element (0) using splice
    // join all the numbers (separated by space)
    const stringOfNumbers = [...Array(n+1).keys()].splice(1).join(' ');
    
    // output the result
    console.log(stringOfNumbers);
    
    0 讨论(0)
  • 2020-12-29 14:28
    let n=0;
    
    for ( i = 1; i <= 10; i++)
        {
          n += i + “ “;
          console.log(n);
    }
    
    0 讨论(0)
  • 2020-12-29 14:36

    In Node.js you can also use the command:

    process.stdout.write()

    This will allow you to avoid adding filler variables to your scope and just print every item from the for loop.

    0 讨论(0)
  • 2020-12-29 14:37

    Build a string then log it after the loop.

    var s = "";
    for(var i = 1; i < 11; i += 1) {
      s += i + " ";
    }
    console.log(s);

    0 讨论(0)
  • 2020-12-29 14:37

    There can be an alternative way to print counters in single row, console.log() put trailing newline without specifying and we cannot omit that.

    let str = '',i=1;
    while(i<=10){
        str += i+'';
        i += 1;
    }
    
    console.log(str);

    0 讨论(0)
提交回复
热议问题