すがブロ

sugamasaoのhatenablogだよ

debug(主にJSONのインスペクト)用スクリプトを置いたよ

以下にあるので、適当に使ってくだしあ!

前回公開したJSを下記に置きました。

前回公開したスクリプトからの変更点

  1. function だった場合は中身を表示しない(出ても大体、うざいだけなので・・・)
  2. あまりに深い階層になった場合は自重する(とりあえず5階層まで行くと深追いしないようにした)

気に食わない部分等があればよしなにしてください。

これを使うと

こんなデータ構造のオブジェクトを

var array = new Array(5, 6);
var func = function(){return "test"}
var data = {
func2:func, // 上で宣言した function だよ
func:func , // 同じく
Array:array , // 上で宣言した Array だよ
hoge:true,
fuga:{test:"test", test2:10, piyo:[10, 20]}
}

こんな風に表示してくれます。

func2:(function)
func:(function)
Array
{
__0:5(number)
__1:6(number)
}
hoge:true(boolean)
fuga
{
__test:test(string)
__test2:10(number)
__piyo
__{
____0:10(number)
____1:20(number)
__}
}

使い方

こんな感じでオブジェクトを生成してメソッドを呼べばおk。

var d = new Debug();
d.writeHTML(hogehoge); // hogehoge という変数をインスペクトする(HTMLに出力)
d.write(hogehoge);     // 同上(alert で表示する版)

ソースはこちら

function Debug() {
  this.initialize.apply(this, arguments);
}

Debug.prototype = {
  initialize: function() {
      this.SEP = "__";
      this.BR = '\n'
      this.HTML_ID = 'debug_write_html';
  },
  inspect: function(obj, dep) {
    var str = "";

    if (typeof(dep) == 'undefined') {
      dep = 0;
    } else if (dep > 5) {
      return str;
    }
    for (var i in obj) {
      var seps = "";
      for(var j = 0; j < dep; j++) {
        seps += this.SEP;
      }
      if (typeof(obj[i]) == 'function') {
        str += seps + i + ":(" + typeof(obj[i])  + ")" + this.BR  
      } else if (typeof(obj[i]) == 'object') {
        str += seps + i + this.BR
        str += seps + "{" + this.BR + this.inspect(obj[i], dep+1);
        str += seps + "}" + this.BR;
      } else {
        str += seps + i + ":" + obj[i] + "("+ typeof(obj[i]) + ")" + this.BR;
      }   
    }   
    return str;
  },  
  writeHTML: function(data) {
    var s = this.inspect(data);
    var t = document.getElementById(this.HTML_ID);
    if (!t) {
      var b = document.getElementsByTagName("body")[0];
      t = this.createHTML();
      b.appendChild(t);
    }   
    if(t.innerHTML != ""){
      s = t.innerHTML + "<hr>"  + s;
    }   
    t.innerHTML = s.replace(new RegExp(this.BR, 'g'), "<br>");
  },  
  write: function(data) {
    alert(this.inspect(data));
  },  
  createHTML: function() {
    var t = document.createElement("div");
    t.setAttribute('id', this.HTML_ID);
    t.style.backgroundColor = "#ffffaa";
    t.style.borderStyle = 'solid';
    t.style.borderColor = '#000000';
    t.style.borderWidth = '1px';
    t.style.margin = '0.5em';
    t.style.padding = '0.5em';
    t.style.position = 'fixed';
    t.style.right = '0px';
    t.style.top = '0px';
    t.style.overflow = 'auto';
    t.style.height = "90%";
    t.style.width = "20%";
    t.style.zIndex = "99";
    return t;
  }
};