如何将console.dir(object)的结果读取/赋值到变量用于JavaScript代码处理?
当然有办法啦!console.dir本质是把对象的完整结构(包括普通console.log可能漏掉的不可枚举属性、原型链细节)格式化输出,要把这些内容存到变量里,其实就是要实现和它类似的对象深度遍历+信息收集逻辑,下面分不同运行场景给你几种实用方案:
浏览器环境下的实现
1. 自定义函数模拟console.dir的完整行为
如果需要在代码里自动获取和console.dir完全一致的对象结构(包括原型链、不可枚举属性),可以写一个递归遍历函数:
function getConsoleDirResult(obj, seen = new WeakSet()) { // 处理循环引用,避免栈溢出 if (seen.has(obj)) return '[Circular Reference]'; seen.add(obj); // 处理基本数据类型和null if (typeof obj !== 'object' || obj === null) { return obj; } const result = {}; let currentObj = obj; // 遍历原型链上的所有属性 while (currentObj !== null) { // 获取当前对象的所有属性名(包括不可枚举的) Object.getOwnPropertyNames(currentObj).forEach(key => { if (!result.hasOwnProperty(key)) { const propDesc = Object.getOwnPropertyDescriptor(currentObj, key); // 区分getter属性和普通属性 result[key] = propDesc.get ? '[Getter]' : getConsoleDirResult(currentObj[key], seen); } }); currentObj = Object.getPrototypeOf(currentObj); } seen.delete(obj); return result; } // 用法示例 const testObj = { name: 'test', nested: { id: 123 } }; // 添加一个不可枚举属性 Object.defineProperty(testObj, 'hiddenProp', { value: '不可见的属性', enumerable: false }); const dirContent = getConsoleDirResult(testObj); console.log(dirContent); // 此时dirContent就包含了和console.dir一致的完整结构
2. 调试场景下的快速方案
如果只是在浏览器控制台临时操作,可以直接用copy()方法:先执行console.dir(yourObject)确认内容,再执行copy(yourObject)把对象完整拷贝到剪贴板,之后就能粘贴到变量里使用(不过这个方法适合手动调试,不适合代码自动处理)。
Node.js环境下的实现
Node.js内置的util.inspect就是console.dir背后使用的工具,直接用它就能得到完全一致的结果:
const util = require('util'); const testObj = { name: 'node-test', nested: { value: 456 } }; Object.defineProperty(testObj, 'secret', { value: '隐藏属性', enumerable: false }); // 获取字符串形式的console.dir结果 const dirString = util.inspect(testObj, { showHidden: true, // 显示不可枚举属性 depth: null, // 无限深度遍历 showPrototype: true // 显示原型链 }); console.log(dirString); // 如果需要对象形式而非字符串,可以结合深度克隆(注意处理循环引用) // Node.js 17+支持的structuredClone,不过它会忽略不可枚举属性和原型链 const clonedObj = structuredClone(testObj);
注意事项
- 循环引用处理:对象如果存在循环引用(比如
obj.self = obj),一定要用WeakSet这类工具追踪已遍历对象,否则会触发栈溢出 - 属性范围:如果不需要原型链和不可枚举属性,用
JSON.stringify加自定义replacer就能快速实现,但它会丢失这些细节:
const seen = new WeakSet(); const simpleResult = JSON.stringify(obj, (key, value) => { if (typeof value === 'object' && value !== null) { if (seen.has(value)) return '[Circular]'; seen.add(value); } return value; }, 2);
内容的提问来源于stack exchange,提问作者klng
相关产品推荐
相关产品推荐

