DIV CSS 佈局教程網

用 Node.js 實作 PHP 的 print_r 函式
編輯:JavaScript綜合知識     

熟悉 PHP 的開發者一定對 print_r 不陌生,它能以易讀格式印出陣列或物件結構。本文示範如何用 Node.js 打造一個功能相近的版本,方便在伺服器端除錯時快速檢視資料。

做法是透過遞迴遍歷物件,判斷屬性是陣列、物件、字串還是其他型別,並以縮排呈現層次:

function ergodic(obj, indentation){
  var indent = " " + indentation;
  if(obj.constructor == Array || obj.constructor == Object){
    for(var p in obj){
      if(obj[p].constructor == Array || obj[p].constructor == Object){
        console.log(indent + "["+p+"] => "+typeof(obj)+"");
        console.log(indent + "{");
        ergodic(obj[p], indent);
        console.log(indent + "}");
      } else if (obj[p].constructor == String) {
        console.log(indent + "["+p+"] => '"+obj[p]+"'");
      } else {
        console.log(indent + "["+p+"] => "+obj[p]+"");
      }
    }
  }
}

外層再包一個 print_r 負責印出最外圍的大括號:

function print_r(obj) {
  console.log("{");
  ergodic(obj, "");
  console.log("}");
}

測試一段巢狀資料即可看到分層效果:

var stu = {'name':'Alan','grade':{'Chinese':120,'math':130,'competition':{'NOI':'First prize'}}};
print_r(stu);

如此一來,即便在 Node.js 環境下,也能享受與 PHP print_r 同樣友善的結構化輸出體驗。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved