JSONObject.toString
作者:快乐笛子 来源:快乐笛子博客 时间:2008-03-09 19:12:00
Object 类型的对象虽然有 toString 方法,但结果却是 [Object Object] 让人没法理解的字符。比如简单的对象:{name:"张三",age:20,canfly:true,sayHello:function(){alert("hello!")},hasPower:["fly","selfFix","autobuilding"]},此对象的数据格式几乎涵盖了JavaScript所有常见的数据格式(字符、数字、布尔、方法、数组),如果执行该对象的toString方法能还原描述此对象的原始字符串,将能更直观地展示对象。
ok,let's go
Object.prototype.toString = function(){
var str = "";
for (var key in this){
if(key=="toJSONString")continue;
if(!this[key] || this[key]==true){
str += ","+key+":"+this[key];
}else if(typeof this[key]=="number"){
str += ","+key+":"+this[key]+"";
}else if(typeof this[key] == "string"){
str += ","+key+":\""+this[key]+"\"";
}else if(typeof this[key]=="function"){
str += ","+key+":"+this[key].toString();
}else if(typeof this[key] == "object"){
if(this[key].constructor == Array){
str += ","+key+":"+this[key].toJSONString();
}else if(this[key].constructor == Object){
str += ","+key+":"+this[key].toString();
}
}
}
return "{"+str.substring(1)+"}";
}
Array.prototype.toJSONString = function(){
var str = "";
for (var key=0; key<this.length; key++){
if(typeof this[key]=="number"){
str += ","+this[key];
}else if(typeof this[key] == "string"){
str += ",\""+this[key]+"\"";
}else if(!this[key] || this[key]==true){
str += ","+this[key];
}else if(typeof this[key]=="function"){
str += ","+this[key].toString();
}else if(typeof this[key] == "object"){
if(this[key].constructor == Array){
str += ","+ this[key].toJSONString();
}else if(this[key].constructor == Object){
str += ","+this[key].toString();
}
}
}
return "["+str.substring(1)+"]";
}
方法很简单,处理的数据格式也仅限于上面提到的几种JavaScript内置数据格式。上面的代码有两段,但不能分拆,互相有引用。