数组的浅/深拷贝

2021-02-05 12:18

阅读:515

标签:方式   length   var   new   副本   lda   col   slice   color   

数组的浅拷贝

改变其中一个另外一个也会变化

直接赋值,var newArr = this.oldArr

数组的深拷贝

改变其中一个数组另一个数组不会变化

1.for循环方式

var arr1 = [1, 2, 3];
var arr2 = [];
for (var i = 0; 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, 

 

数组的浅/深拷贝

标签:方式   length   var   new   副本   lda   col   slice   color   

原文地址:https://www.cnblogs.com/zhaohui-116/p/12788738.html


评论


亲,登录后才可以留言!