js的浅拷贝和深拷贝

转载:http://www.jb51.net/article/91906.htm

  //深拷贝,并且把合并后的值放到第二个参数里
function deepCopy(p, c) {
    var c = c || {};
      for (var i in p) {
          if (typeof p[i] === 'object') {
              c[i] = (p[i].constructor === Array) ? [] : {};
                  deepCopy(p[i], c[i]);
                    } else {
                          c[i] = p[i];
                    }
            }
          return c;
}

var s = {
name:"bob",
age:20,
sex:"man",
like:["basketball","soccer","pingpang"]
}
var ss = {
girl:"dan"
}
var result = deepCopy(s,ss);
console.log(result);
console.log(ss);
console.log(s);

 

 

 

posted @ 2016-11-12 19:12  飘然离去  阅读(180)  评论(0编辑  收藏  举报