数组的浅拷贝
改变其中一个另外一个也会变化
直接赋值,var newArr = this.oldArr
数组的深拷贝
改变其中一个数组另一个数组不会变化
1.for循环方式
var arr1 = [1, 2, 3]; var arr2 = []; for (var i = 0; i < arr1.length; i++) { arr2.push(arr1[i]); } arr1[0] = 4; console.log(arr1); //4, 2, 3 console.log(arr2); //1, 2, 3
2.concat方法,连接两个数组,不会改变原始数组,返回一个副本
var arr1 = [1, 2, 3]; var arr2 = arr1.concat(); arr1[0] = 4; console.log(arr1); //4, 2, 3 console.log(arr2); //1, 2, 3
3.slice方法,截取数组,
var arr1 = [1, 2, 3]; var arr2 = arr1.slice(0); arr1[0] = 4; console.log(arr1); //4, 2, 3 console.log(arr2); //1, 2, 3
4.ES6扩展运算符实现数组的深拷贝
var arr1 = [1, 2, 3]; var [...arr2] = arr1; arr1[0] = 4; console.log(arr1); //4, 2, 3 console.log(arr2); //1, 2,