• 数组的深拷贝和浅拷贝


    数组浅拷贝:

    var arr1 = [1, 2, 3, 4];
    var arr2 = arr1; 
    arr1[0] = 6;                //数组是用堆去保存的,相等的时候只是把存放的地址拷贝过去了,两个指向了同一个地址,所以在改变其中一个的值,其他的也跟着改变了
    console.log(arr2[0]);       //输出结果为6
    console.log(arr[1]);        //[6, 2, 3, 4]
    console.log(arr[2]);        //[6, 2, 3, 4]

    数组深拷贝:

    1)、slice方法:

    var arr1 = [1, 2, 3, 4];
    var arr2 = arr1.slice(0);   //从0开始到末尾截取数组,然后返回一个新的数组
    arr1[0] = 6; 
    console.log(arr2[0]);       //输出结果为1
    console.log(arr[1]);        //[6, 2, 3, 4]
    console.log(arr[2]);        //[1, 2, 3, 4]

    2)、concat方法:

    var arr1 = [1, 2, 3, 4];
    var arr2 = arr1.concat();   //连接数组,如果连接的是一个空,那么也是返回了新的本身的数组
    arr1[0] = 6; 
    console.log(arr2[0]);       //输出结果为1
    console.log(arr[1]);        //[6, 2, 3, 4]
    console.log(arr[2]);        //[1, 2, 3, 4]

    3)、map方法:

    var arr1 = [1, 2, 3, 4]; 
    var arr2 = arr1.map(function(value){
         return value;
    })                          //使用map方法遍历数组然后返回新的数组,里面的值不变
    arr1[0] = 6;   
    console.log(arr2[0])        //输出结果为1
    console.log(arr1);          //[6, 2, 3, 4]
    console.log(arr2);          //[1, 2, 3, 4]

    4)、ES6语法:

    var arr1 = [1, 2, 3, 4];
    var [ ...arr2 ] = arr1;     //ES6扩展运算符实现数组的深拷贝
    arr1[0] = 6; 
    console.log(arr2[0]);       //输出结果为1
    console.log(arr[1]);        //[6, 2, 3, 4]
    console.log(arr[2]);        //[1, 2, 3, 4]
  • 相关阅读:
    IEnumerator & IEnumerable
    GameObject.Active
    Unity3D的四种坐标系
    gvim
    Platform Dependent Compilation
    delegate
    new 约束
    UIPanel
    UIButton
    UISprite
  • 原文地址:https://www.cnblogs.com/mix88/p/11426324.html
Copyright © 2020-2023  润新知