现在的位置: 首页 > 综合 > 正文

json对象转化成json的字符串、克隆对象

2018年02月04日 ⁄ 综合 ⁄ 共 1729字 ⁄ 字号 评论关闭

// 克隆对象

Object.prototype.deep_clone = function(){

    // 不同于这个代码var tmp = this.toJSON();这段代码是将一个字符串赋值给变量

   //  等同于这个代码

       var  tmp  =  {...};
    eval("var tmp = " + this.toJSON());
     return tmp;
};

 

//  下面就是toJSON的实现,具体思路是,将所有的类型的数据都实现toJSON的方法,比较不好实现的就是结构复杂的类型,有两种,一种是Object另一种是数组
Object.prototype.toJSON = function(){
 var json = [];
    // 遍历对象
 for(var i in this){
        // 如果没有属性就下一个,有属性就执行下面的代码
  if(!this.hasOwnProperty(i)) continue;
  //if(typeof this[i] == "function") continue;
       
        // 如果为空就赋值为空,如果不为空就按照所属对象进行相应的转化
  json.push(
   i.toJSON() + " : "
   + ((this[i] != null) ? this[i].toJSON() : "null")
  )
 }
   
 return "{/n " + json.join(",/n ") + "/n}";
};

//数组转化成json
Array.prototype.toJSON = function(){
   
 for(var i=0,json=[];i<this.length;i++){
        // 如果不为空就转化成对应的类型的tojson
        json[i] = (this[i] != null) ? this[i].toJSON() : "null";
    }

 return "["+json.join(", ")+"]"
};

//字符串的tojson方法
String.prototype.toJSON = function(){
    //在string对象值的前后加上双引号
 return '"' +
        // 转义,如果是遇到了反斜杠和双引号就加个
  this.replace(/(//|/")/g,"//$1")
  .replace(//n|/r|/t/g,function(){
   var a = arguments[0];
            // 如果是遇到了/n、/r、/t就直接返回它们的值
   return  (a == '/n') ? '//n':
     (a == '/r') ? '//r':
     (a == '/t') ? '//t': ""
  })
  + '"'
};
Boolean.prototype.toJSON = function(){return this};
Function.prototype.toJSON = function(){return this};
Number.prototype.toJSON = function(){return '"' + this + '"'};
RegExp.prototype.toJSON = function(){return this};

// strict but slow 另一种比较严格的实现,但是比较慢
String.prototype.toJSON = function(){
 var tmp = this.split("");
 for(var i=0;i<tmp.length;i++){
  var c = tmp[i];
  (c >= ' ') ?
   (c == '//') ? (tmp[i] = '////'):
   (c == '"')  ? (tmp[i] = '//"' ): 0 :
  (tmp[i] =
   (c == '/n') ? '//n' :
   (c == '/r') ? '//r' :
   (c == '/t') ? '//t' :
   (c == '/b') ? '//b' :
   (c == '/f') ? '//f' :
   (c = c.charCodeAt(),('//u00' + ((c>15)?1:0)+(c%16)))
  )
 }
   
 return '"' + tmp.join("") + '"';
};

抱歉!评论已关闭.