Javascript for loop console print in one line

给你一囗甜甜゛ 提交于 2019-12-18 12:43:35

问题


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);
}

Right now it's

1
2
3
4
5
6
7
8
9
10

How can I get the output all in one line (like this 1 2 3 4 5 6 7 8 9 10)?


回答1:


Build a string then log it after the loop.

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



回答2:


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!




回答3:


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);



回答4:


// 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);



回答5:


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.



来源:https://stackoverflow.com/questions/33089739/javascript-for-loop-console-print-in-one-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!