PHP 的 print_r() 能直觀輸出陣列/物件的巢狀結構,是除錯利器。Node.js 原生 console.log 輸出物件雖可展開,但在終端機、日誌檔、非互動環境中可讀性較差。本文實作一個支援巢狀縮排、型別標註、循環引用檢測的 print_r 複刻版。
function ergodic(obj, indentation = '') {
const indent = ' ' + indentation;
if (Array.isArray(obj) || (obj && typeof obj === 'object' && obj.constructor === Object)) {
for (const key in obj) {
if (!Object.prototype.hasOwnProperty.call(obj, key)) continue;
const val = obj[key];
const type = Array.isArray(val) ? 'Array' :
val && typeof val === 'object' ? 'Object' :
typeof val;
if (type === 'Array' || type === 'Object') {
console.log(`${indent}[${key}] => ${type}`);
console.log(`${indent}{`);
ergodic(val, indent);
console.log(`${indent}}`);
} else if (type === 'string') {
console.log(`${indent}[${key}] => '${val}'`);
} else {
console.log(`${indent}[${key}] => ${val}`);
}
}
}
}
function print_r(obj) {
console.log('{');
ergodic(obj, '');
console.log('}');
}
// 測試
const stu = {
name: 'Alan',
grade: {
Chinese: 120,
math: 130,
competition: { NOI: 'First prize' }
}
};
print_r(stu);
{
[name] => 'Alan'
[grade] => Object
{
[Chinese] => 120
[math] => 130
[competition] => Object
{
[NOI] => 'First prize'
}
}
}
const util = require('util');
function print_r(obj, options = {}) {
const {
depth = 10, // 最大遞迴深度
colors = true, // 終端機顏色
maxArrayLength = 50, // 陣列最大顯示元素
showHidden = false, // 顯示不可枚舉屬性
showProxy = false, // 顯示 Proxy 內部
sorted = true, // 鍵值排序
getters = false, // 顯示 getter
} = options;
// 利用 Node 內建 util.inspect,功能極其強大
console.log(util.inspect(obj, {
depth, colors, maxArrayLength, showHidden,
showProxy, sorted, getters,
compact: false // 關鍵:非緊湊模式,每層換行
}));
}
| 選項 | 預設 | 說明 |
|---|---|---|
depth | 2 | 遞迴深度,null 為無限 |
colors | false | ANSI 顏色輸出 |
compact | true | 設 false 獲多行縮排輸出 |
maxArrayLength | 100 | 陣列截斷閾值 |
breakLength | 80 | 單行最大長度 |
sorted | true | 鍵值排序 |
getters | false | 執行 getter 並顯示 |
const a = { name: 'a' };
const b = { name: 'b', ref: a };
a.ref = b; // 循環引用
print_r(a);
// util.inspect 會自動標記 [Circular] 避免無限遞迴
// { name: 'a', ref: { name: 'b', ref: [Circular] } }
inspect 客製化class Person {
constructor(name, age) { this.name = name; this.age = age; }
// Node.js 會自動呼叫此方法
[util.inspect.custom](depth, opts) {
if (depth < 0) return '[Person]';
return `Person { name: ${this.name}, age: ${this.age} }`;
}
}
print_r(new Person('Alice', 30));
// Person { name: Alice, age: 30 }
// 瀏覽器無 util.inspect,可用 JSON.stringify 美化
function print_r(obj) {
console.log(JSON.stringify(obj, (key, val) => {
if (typeof val === 'bigint') return val.toString() + 'n';
return val;
}, 2)); // 2 空格縮排
}
// 或引入 tiny-inspect 等輕量庫
util.inspect(obj, { compact: false }),功能完備、效能優化、支援循環引用、可客製化console.log(obj) 互動式展開最好用;日誌用 JSON.stringify善用結構化輸出工具,能大幅提升除錯效率,讓複雜資料結構一目了然。