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

数组的深拷贝与浅拷贝

时间:2020-05-29 11:49:55      阅读:53      评论:0      收藏:0      [点我收藏+]

标签:取数   扩展运算   返回   port   UNC   title   浅拷贝   连接   script   

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数组的深拷贝与浅拷贝</title>
</head>
<body>
    <script>
        //数组的浅拷贝
        var arr1= [1,23,5,1,3];
        var arr2 = arr1;
        arr1[0] = 99;
        console.log(arr1[0]);
        console.log(arr2[0]);
        console.log(arr1);
        console.log(arr2);
        //数组的深拷贝
        var arr3 = arr1.concat();  //连接数组,如果连接的是一个空,那么也是返回了新的本身的数组
        console.log(arr3);
        arr1[0]= 100;
        console.log("arr1: "+arr1[0]);
        console.log("arr3: "+arr3[0]);
        console.log("arr1: "+arr1);
        console.log("arr3: "+arr3);

        var arr4 = arr1.slice(0);  //从0开始到末尾截取数组,然后返回一个新的数组
        arr1[0]= 88;
        console.log("arr1: "+arr1[0]);
        console.log("arr4: "+arr4[0]);
        console.log("arr1: "+arr1);
        console.log("arr4: "+arr4);

        var arr5 = arr1.map(function(value){  //使用map方法遍历数组然后返回新的数组,里面的值不变
           return value;
        })
        arr1[0]= 77;
        console.log("arr1: "+arr1[0]);
        console.log("arr5: "+arr5[0]);
        console.log("arr1: "+arr1);
        console.log("arr5: "+arr5);

        var [...arr6] = arr1//ES6扩展运算符实现数组的深拷贝
        arr1[0]= 66;
        console.log("arr1: "+arr1[0]);
        console.log("arr6: "+arr6[0]);
        console.log("arr1: "+arr1);
        console.log("arr6: "+arr6);

    </script>
</body>
</html>

  

数组的深拷贝与浅拷贝

标签:取数   扩展运算   返回   port   UNC   title   浅拷贝   连接   script   

原文地址:https://www.cnblogs.com/shine1234/p/12986471.html

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