首页 > 代码库 > js的浅拷贝和深拷贝

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);

技术分享

 

 

 

js的浅拷贝和深拷贝