node console.log() output array in one line

大城市里の小女人 提交于 2020-06-16 03:07:39

问题


I use node v10.6.0.

Here's my codes:

console.log([{a:1, b:2}, {a:1, b:2}, {a:1, b:2}])
console.log([{a:1, b:2}, {a:1, b:2}, {a:1, b:2}, {a:1, b:2}, {a:1, b:2}, {a:1, b:2}, {a:1, b:2}, {a:1, b:2}, {a:1, b:2}])

the output is as following:

[ { a: 1, b: 2 }, { a: 1, b: 2 }, { a: 1, b: 2 } ]
[ { a: 1, b: 2 },
  { a: 1, b: 2 },
  { a: 1, b: 2 },
  { a: 1, b: 2 },
  { a: 1, b: 2 },
  { a: 1, b: 2 },
  { a: 1, b: 2 },
  { a: 1, b: 2 },
  { a: 1, b: 2 } ]

How can I make the second array output in one line, instead of spreading to multiple lines.


回答1:


Although the output is not exactly the same as if console.log is used, it's possible to use JSON.stringify to convert the array to a string, then print it:

console.log(JSON.stringify(array))

Try it online!

It cannot process circular structures, however.




回答2:


I suggest using the following:

console.log(util.inspect(array, {breakLength: Infinity}))

Plus, util.inspect has a bunch of extra options to format and limit the output:

https://nodejs.org/api/util.html#util_util_inspect_object_options



来源:https://stackoverflow.com/questions/51573010/node-console-log-output-array-in-one-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!