使用控制台登录 javascript 打印输出同一行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28620087/
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
printing output same line using console log in javascript
提问by BBKay
I have a question that is it possible to print the output in the same line by using console.log in JavaScript? I know console.log always a new line. For example:
我有一个问题,是否可以通过在 JavaScript 中使用 console.log 在同一行中打印输出?我知道 console.log 总是一个新行。例如:
"0,1,2,3,4,5,"
Thanks in advance!
提前致谢!
采纳答案by Michael.Lumley
Couldn't you just put them in the same call, or use a loop?
你不能把它们放在同一个调用中,或者使用循环吗?
var one = "1"
var two = "2"
var three = "3"
var combinedString = one + ", " + two + ", " + three
console.log(combinedString) // "1, 2, 3"
console.log(one + ", " + two + ", " + three) // "1, 2, 3"
var array = ["1", "2", "3"];
var string = "";
array.forEach(function(element){
string += element;
});
console.log(string); //123
回答by Alex Glukhovtsev
in nodejs there is a way:
process.stdout
so, this may work:process.stdout.write(`${index},`);
where: indexis a current data and ,is a delimiter
also you can check same topic here
在nodejs中有一种方法:
process.stdout
所以,这可能有效:process.stdout.write(`${index},`);
其中:index是当前数据并且,是分隔符,
您也可以在此处查看相同的主题
回答by Jim-chriss Charles
You could just use the spread operator ...
你可以只使用传播运算符 ...
var array = ['a', 'b', 'c'];
console.log(...array);
回答by Mrigank Khemka
So if you want to print numbers from 1 to 5 you could do the following:
因此,如果您想打印 1 到 5 之间的数字,您可以执行以下操作:
var array = [];
for(var i = 1; i <= 5; i++)
{
array.push(i);
}
console.log(array.join(','));
Output: '1,2,3,4,5'
输出:'1,2,3,4,5'
Array.join(); is a very useful function that returns a string by concatenating the elements of an array. Whatever string you pass as parameter is inserted between all the elements.
Array.join(); 是一个非常有用的函数,它通过连接数组元素返回一个字符串。您作为参数传递的任何字符串都会插入到所有元素之间。
Hope it helped!
希望有帮助!
回答by bitbyte
You can just console.logthe strings all in the same line, as so:
您可以console.log将所有字符串都放在同一行中,如下所示:
console.log("1" + "2" + "3");
And to create a new line, use \n:
要创建一个新行,请使用\n:
console.log("1,2,3\n4,5,6")
If you are running your app on node.js, you can use an ansi escape codeto clear the line \u001b[2K\u001b[0E:
如果您在 node.js 上运行您的应用程序,您可以使用ansi 转义码来清除该行\u001b[2K\u001b[0E:
console.log("old text\u001b[2K\u001b[0Enew text")
回答by Taha Paksu
You can print them as an array
您可以将它们打印为数组
if you write:
如果你写:
console.log([var1,var2,var3,var4]);
you can get
你可以得到
[1,2,3,4]
回答by Dhwaj Kothari
You can also use the spread operator (...)
您还可以使用扩展运算符 (...)
console.log(...array);
The "Spread" operator will feed all the elements of your array to the console.log function.
“Spread”运算符会将数组的所有元素提供给 console.log 函数。

