用于循环控制台打印的 Javascript 一行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33089739/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript for loop console print in one line
提问by CH-SO
I'm trying to get the output from my for loop to print in a single line in the console.
我试图从我的 for 循环中获取输出以在控制台中的一行中打印。
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 2 3 4 5 6 7 8 9 10
)?
回答by Dave
Build a string then log it after the loop.
构建一个字符串,然后在循环后记录它。
var s = "";
for(var i = 1; i < 11; i += 1) {
s += i + " ";
}
console.log(s);
回答by Artemis
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!
继续前进并学习东西!祝你好运!
回答by jasmeetsohal
There can be an alternative way to print counters in single row, console.log() put trailing newline without specifying and we cannot omit that.
可以有一种在单行中打印计数器的替代方法,console.log() 在不指定的情况下放置尾随换行符,我们不能省略它。
let str = '',i=1;
while(i<=10){
str += i+'';
i += 1;
}
console.log(str);
回答by Yiin
// 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);
回答by user11073489
In Node.js you can also use the command:
在 Node.js 中,您还可以使用以下命令:
process.stdout.write()
process.stdout.write()
This will allow you to avoid adding filler variables to your scope and just print every item from the for loop.
这将允许您避免向作用域添加填充变量,而只需打印 for 循环中的每个项目。