简体   繁体   English

无论如何,console.log 没有换行符吗?

[英]Is there anyway to console.log without a newline?

I want to console.log() my array like this without newlines我想在没有换行符的情况下像这样console.log()我的数组

let myarr = [1,2,3,4,5];
myarr.forEach(e => console.log(e));

You could spread the array.你可以传播阵列。 Then all values are taken as parameters.然后将所有值作为参数。

 let array = [1, 2, 3, 4, 5]; console.log(...array);

You can use .reduce() instead.您可以使用.reduce()代替。

 let myarr = [1,2,3,4,5]; const result = myarr.reduce((a, c) => `${a}${c}`, ''); console.log(result);

I hope this helps!我希望这有帮助!

Why are you doing a separate console.log for every element in the array?为什么要为数组中的每个元素都做一个单独的 console.log? You can just do:你可以这样做:

console.log(myarr);

Or, if your array has objects in it and you want to see them all unrolled, you could do:或者,如果您的数组中有对象并且您希望看到它们全部展开,您可以执行以下操作:

console.log(JSON.stringify(myarr));

You would have to stringify your output.您必须对输出进行字符串化。

So either using something like JSON.stringify(myarr) or所以要么使用像JSON.stringify(myarr)类的东西,要么

let string = '';
for(let i = 1; i < 6; i += 1) {
  string += i + ' ';
}
console.log(string);

Edit: Btw, I'd suggest using camelCase when working with javascript.编辑:顺便说一句,我建议在使用 javascript 时使用camelCase。 It's become a standard when defining variables and methods.它已成为定义变量和方法时的标准。

See: https://techterms.com/definition/camelcase请参阅: https : //techterms.com/definition/camelcase

To answer the actual question, there are two possible answers:要回答实际问题,有两种可能的答案:

  1. If you are running in a browser, then by default, no, but according to this answer from Chrome JavaScript developer console: Is it possible to call console.log() without a newline?如果您在浏览器中运行,则默认情况下不可以,但根据Chrome JavaScript 开发人员控制台的回答:是否可以在没有换行符的情况下调用 console.log()? you can by making a virtual console on top of the browser's console.您可以通过在浏览器的控制台上创建一个虚拟控制台。
  2. If you're using node, then you can use process.stdout.write(msg) from this answer Chrome JavaScript developer console: Is it possible to call console.log() without a newline?如果您使用的是节点,那么您可以使用这个答案中的process.stdout.write(msg) Chrome JavaScript 开发人员控制台:是否可以在没有换行符的情况下调用 console.log()?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM