美文网首页
JS 浅拷贝与深拷贝

JS 浅拷贝与深拷贝

作者: 麻辣小面瘫 | 来源:发表于2018-01-15 21:45 被阅读0次

    1.浅拷贝(引用类型的复制都是浅拷贝)

    var arr1 = [1,2,3,4];
    arr2 = arr1;
    arr2.push(5);
    console.log(arr1);//[1,2,3,4,5]
    

    2.对象的浅拷贝

    function copy(obj){
      var tempObj = {};
      for(var i in obj){
        tempObj[i] = obj[i]; //属性复制
      }
      return tempObj
    }
    var Person = {
      name:'person',
      skills:['g','s','m']
    }
    var newPerson = copy(Person);
    console.log(Person.skills ) ;//['g','s','m'];
    newPerson.skills.push('b');
    console.log(Person.skills); // ['g','s','m','b']; 浅拷贝,只是拷贝了指向引用类型的地址
    console.log(newPerson .skills); // ['g','s','m','b']; 
    

    2.对象的深拷贝(在浅拷贝的基础上递归调用)

    function deepCopy(obj, newObj) {
      var tempObj= newObj || {};
      for (var i in obj) {
        if (typeof obj[i] === 'object') {
          tempObj[i] = (obj[i].constructor === Array) ? [] : {};
          deepCopy(obj[i], tempObj[i]);
        } else {
          tempObj[i] = obj[i];
        }
      }
      return tempObj;
    };
    var Person = {
      name:'person',
      skills:['g','s','m']
    }
    var newPerson = deepCopy(Person);
    console.log(Person.skills ) ;//['g','s','m'];
    newPerson.skills.push('b');
    console.log(Person.skills); // ['g','s','m']; 
    console.log(newPerson .skills); // ['g','s','m','b']; 
    

    相关文章

      网友评论

          本文标题:JS 浅拷贝与深拷贝

          本文链接:https://www.haomeiwen.com/subject/bbxjoxtx.html