2007-06-09

QopDump - Dump 的 AS3 版

改寫以前 AS2 的 Dump
使用方式
var a:Object = ["sd","tg","rt",{a:"1", b:"23", c:"11"}];
// 取得字串資料用 QopDump.go(a)
// 直接 trace
QopDump.echo(a);

執行結果:
[0]:sd
[1]:tg
[2]:rt
[3]:
c:11
a:1
b:23

原始檔 QopDump.as
/**
* author: shinder lin
* email: shinder.lin@gmail.com
*/
package {
import flash.utils.describeType;
public class QopDump {
static var n:int = 0;
static var str:String;
// trace
public static function echo(o:Object):void {
trace( go(o) );
}
// return the result string
public static function go(o:Object):String {
str = "";
dump(o);
// remove the lastest \n
str = str.slice(0, str.length-1);
return str;
}
static function dump(o:Object) {
var type:String = describeType(o).@name;
if(type == 'Array') {
dumpArray(o);
} else if (type == 'Object') {
dumpObject(o);
} else {
appendStr(o);
}
}
static function appendStr(s:Object) {
str += s + '\n';
}
static function dumpArray(a:Object):void {
n++;
var type:String;
for (var i:String in a) {
type = describeType(a[i]).@name;
if (type == 'Array' || type == 'Object') {
appendStr(getSpaces() + "[" + i + "]:");
dump(a[i]);
} else {
appendStr(getSpaces() + "[" + i + "]:" + a[i]);
}
}
n--;
}
static function dumpObject(o:Object):void {
n++;
var type:String;
for (var i:String in o) {
type = describeType(o[i]).@name;
if (type == 'Array' || type == 'Object') {
appendStr(getSpaces() + i + ":");
dump(o[i]);
} else {
appendStr(getSpaces() + i + ":" + o[i]);
}
}
n--;
}
static function getSpaces():String {
var s:String ="";
for(var i:int = 1; i < n; i++){
s += " ";
}
return s;
}
}
}

沒有留言:

FB 留言