如何在CLI控制台日志中展开[Array]或[Object]显示完整值?
解决CLI打印变量时[Array]/[Object]不展开的问题
以下几种方法可以让CLI打印时完整展示数组和对象内容:
使用
console.dir()并配置深度
这是Node.js环境下最直接的方式,通过指定depth: null来递归展开所有嵌套层级:console.dir(yourTargetVariable, { depth: null });用
JSON.stringify()格式化输出
适合需要JSON格式输出的场景,还能指定缩进让内容更易读:console.log(JSON.stringify(yourTargetVariable, null, 2));注意:如果变量里有循环引用、函数或Symbol类型,这种方法会忽略或报错,需根据实际场景选择。
全局设置Node.js的inspect默认选项
如果希望所有console.log()都自动展开内容,可以在代码开头配置全局选项:require('util').inspect.defaultOptions.depth = null;之后直接用
console.log(yourTargetVariable)就能看到完整的嵌套内容了。
内容的提问来源于stack exchange,提问作者Luke
相关产品推荐
相关产品推荐

