BBK*_*Kay 14 javascript logging
我有一个问题是可以在JavaScript中使用console.log在同一行中打印输出吗?我知道console.log总是一个新行.例如:
"0,1,2,3,4,5,"
Run Code Online (Sandbox Code Playgroud)
提前致谢!
Ale*_*sev 29
在nodejs中有一种方法:
process.stdout
所以,这可能有效:
process.stdout.write(`${index},`);
where:index是当前数据,,也是分隔符,
你也可以在这里检查相同的主题
小智 10
因此,如果您想打印 1 到 5 之间的数字,您可以执行以下操作:
var array = [];
for(var i = 1; i <= 5; i++)
{
array.push(i);
}
console.log(array.join(','));Run Code Online (Sandbox Code Playgroud)
输出:'1,2,3,4,5'
Array.join(); 是一个非常有用的函数,它通过连接数组元素返回一个字符串。您作为参数传递的任何字符串都会插入到所有元素之间。
希望有帮助!
小智 7
您可以只使用点差运算符 ...
var array = ['a', 'b', 'c'];
console.log(...array);Run Code Online (Sandbox Code Playgroud)
小智 6
您可以console.log将所有字符串都放在同一行中,如下所示:
console.log("1" + "2" + "3");
Run Code Online (Sandbox Code Playgroud)
要创建一个新行,请使用\n:
console.log("1,2,3\n4,5,6")
Run Code Online (Sandbox Code Playgroud)
如果您在 node.js 上运行您的应用程序,您可以使用ansi 转义码来清除该行\u001b[2K\u001b[0E:
console.log("old text\u001b[2K\u001b[0Enew text")
Run Code Online (Sandbox Code Playgroud)
您不能将它们放在同一呼叫中,还是使用循环?
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
Run Code Online (Sandbox Code Playgroud)