js数组对象复制拷贝不改变原来的值,深拷贝

js数组,对象复制拷贝,深拷贝,按值传递

数组拷贝

方法1

es6扩展运算符


let arr1 = [1, 2, 3],
  arr2 = [...arr1];
arr2.pop();
 
console.log(arr1);
console.log(arr2);
 

2Object.assign()

let arr1 = [1, 2, 3],
    arr2 = [];
Object.assign(arr2,arr1)
arr2.pop();
console.log(arr1);
console.log(arr2);


> Array [1, 2, 3]
> Array [1, 2]

3 concat

let arr1 = [1, 2, 3],
  arr2 = arr1.concat();     
arr2.pop();
console.log(arr1);
console.log(arr2);

4Array.form

 

let arr1 = [1, 2, 3],
  arr2 = Array.from(arr1); 
arr2.splice(0, 1);
console.log(arr1);
console.log(arr2);

 5 push.apply

 

let arr1 = [1, 2, 3],
    arr2 = [];
arr2.push.apply(arr2, arr1);
arr2.pop();
console.log(arr1);
console.log(arr2);

6 slice

 

let arr1 = [1, 2, 3],
    arr2 = arr1.slice();
arr2.pop();
console.log(arr1);
console.log(arr2);

7 json

let arr1 = [1, 2, 3],
    arr2 = JSON.parse(JSON.stringify(arr1));
arr2.pop();
console.log(arr1);
console.log(arr2);

 对象拷贝

let a = {name : "liming",
    id :1},
    b = Object.assign({},a);
b.id = 2;
console.log(a);
console.log(b);

> Object { name: "liming", id: 1 }
> Object { name: "liming", id: 2 }

数组中有对象

let a = [1,2,3,{name : "liming",
        id :1}],
    b = JSON.parse(JSON.stringify(a));
b[3].id = 2;
console.log(a);
console.log(b);

> Array [1, 2, 3, Object { name: "liming", id: 1 }]
> Array [1, 2, 3, Object { name: "liming", id: 2 }]

 

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页