码迷,mamicode.com
首页 > 编程语言 > 详细

数组和对象的深拷贝

时间:2016-07-12 11:56:47      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:

一、数组的深拷贝

  var arr = ["one", "two", "three"];

  var arrCopy = arr;

  arrCopy[1] = "test";

  console.log(arr);       //["one", "test", "three"]

  console.log(arrCopy);    //["one", "test", "three"]

  1.如果直接将一个数组赋值给另一个数组,那么改变其中一个,另一个也会改变,这是数组的浅拷贝

  2.解决方案:利用数组的slice和concat方法,这两个方法都在不会改变原数组的基础上而产生一个新数组。  

    var arr = ["one", "two", "three"];

    var arrCopy = arr.slcie(0);  // arrCopy = arr.concat();

    arrCopy[1] = "test";

    console.log(arr);       //["one", "two", "three"]

    console.log(arrCopy);    //["one", "test", "three"]

二、对象的深拷贝

  var json = {name: "aaa", age: 12};

  var jsonCopy = json;

  jsonCopy.name = "bbb";

  console.log(json);       // {name: "bbb", age: 12}

  console.log(jsonCopy);    // {name: "bbb", age: 12}

  1.同理,对象这样直接赋值也是浅拷贝

  2.解决方案:就是把对象的属性遍历一遍,赋给一个新的对象。

    var json = {name: "aaa", age: 12};

    var jsonCopy = new Object();

    jsonCopy.name = json.name;

    jsonCopy.age = json.age;

    jsonCopy.name = "bbb";

    console.log(json);       // {name: "aaa", age: 12}

    console.log(jsonCopy);    // {name: "bbb", age: 12}

  

  var deepCopy = function(source) {
    var result={};
    for (var key in source) {
      result[key] = typeof source[key]===‘object‘? deepCopy(source[key]): source[key];
    }
    return result;
  }

数组和对象的深拷贝

标签:

原文地址:http://www.cnblogs.com/isnan/p/5662746.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!