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 }]