数组的深拷贝与浅拷贝
Posted shine1234
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了数组的深拷贝与浅拷贝相关的知识,希望对你有一定的参考价值。
<!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>
以上是关于数组的深拷贝与浅拷贝的主要内容,如果未能解决你的问题,请参考以下文章