node console.log() 一行输出数组

node console.log() output array in one line

我使用节点v10.6.0

这是我的代码:

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}])

输出如下:

[ { 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 } ]

如何让第二个数组在一行中输出,而不是分散到多行。

虽然输出与使用 console.log 不完全相同,但可以使用 JSON.stringify 将数组转换为字符串,然后打印它:

console.log(JSON.stringify(array))

Try it online!

但是,它不能处理圆形结构。

我建议使用以下内容:

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

另外,util.inspect 有一堆额外的选项来格式化和限制输出:

https://nodejs.org/api/util.html#utilinspectobject-options

为什么不使用 console.table 呢?

这很好table: https://tio.run/##y0osSyxOLsosKNHNy09J/Z9YVJRYaRtdnWhlqKOQZGVUq6NAW3bs/@T8vOL8nFS9ksSknFQNsAM0//8HAA

┌─────────┬───┬───┐
│ (index) │ a │ b │
├─────────┼───┼───┤
│    0    │ 1 │ 2 │
│    1    │ 1 │ 2 │
│    2    │ 1 │ 2 │
│    3    │ 1 │ 2 │
│    4    │ 1 │ 2 │
│    5    │ 1 │ 2 │
│    6    │ 1 │ 2 │
│    7    │ 1 │ 2 │
│    8    │ 1 │ 2 │
└─────────┴───┴───┘