[英]print the number in this form using javascript display output on console.log
[英]Print an output in one line using console.log()
是否可以在 JavaScript 中使用
console.log()<\/code>在同一行打印输出?
我知道
console.log()<\/code>总是返回一个新行。
例如,让多个连续
console.log()<\/code>调用的输出为:
"0,1,2,3,4,5,"
你可以只使用传播运算符...
var array = ['a', 'b', 'c']; console.log(...array);
你不能把它们放在同一个调用中,或者使用循环吗?
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
因此,如果您想打印 1 到 5 之间的数字,您可以执行以下操作:
var array = []; for(var i = 1; i <= 5; i++) { array.push(i); } console.log(array.join(','));
输出:'1,2,3,4,5'
Array.join(); 是一个非常有用的函数,它通过连接数组元素返回一个字符串。 您作为参数传递的任何字符串都会插入到所有元素之间。
希望有帮助!
您可以只在同一行中console.log
字符串,如下所示:
console.log("1" + "2" + "3");
要创建一个新行,请使用\\n
:
console.log("1,2,3\n4,5,6")
如果您在 node.js 上运行您的应用程序,您可以使用ansi 转义码来清除行\[2K\[0E
:
console.log("old text\u001b[2K\u001b[0Enew text")
直接在浏览器环境中是不可能的。 您需要创建一些缓冲区来保存要在同一行上打印的值。
在以前的答案中有使用数组和循环的示例。 作为替代方案,您可以在功能上解决它:
const print = ((buffer = '') => arg => { if (arg !== '\\n') { buffer += arg } else { console.log(buffer) buffer = '' } })() print('x') print('y') print('z') print('\\n') // flush buffer
或者您可以使用对象设置器
const c = { buffer: '', set log(val) { if (val !== '\\n') { this.buffer += val } else { console.log(this.buffer) this.buffer = '' } } } c.log = 'foo' c.log = 42 c.log = 'bar' c.log = '\\n'
您可以将它们打印为数组
如果你写:
console.log([var1,var2,var3,var4]);
你可以得到
[1,2,3,4]
您还可以使用扩展运算符(...)
console.log(...array);
“Spread”运算符会将数组的所有元素提供给console.log
函数。
您可以使用扩展运算符。 “log”方法将它的参数打印在一行中,您可以通过展开数组将数组的元素作为单独的参数提供给它。
console.log(... array);
您可以使用逗号分隔符:
console.log(1,2,3,4);
但是如果您希望逗号出现在输出中,那么您将需要使用字符串:
console.log('1,','2,','3,','4');
你也可以这样做:
let s = ""; for (let i = 0; i < 6; i++) { s += i.toString(); if (i != 5) { s += ","; } } console.log(s);
你可以这样做。 这很简单。
var first_name = ["Ram", "Sita", "Hari", "Ravi", "Babu"];
name_list = "";
name_list += first_name;
console.log(name_list);
// OR you can just typecast to String to print them in a single line separated by comma as follows;
console.log(first_name.toString());
// OR just do the following
console.log(""+first_name);
// Output: Ram,Sita,Hari,Ravi,Babu
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.