深拷贝
数组5种拷贝
1.for循环
var arr1 = [1, 2, 3,true, false,];
var arr2 = copyArr(arr1);
function copyArr(arr) {
let res = [];
for (let i = 0, length = arr.length; i < length; i++) {
res.push(arr[i]);
}
return res;
}
console.log(arr2);
2.slice
let arr1 = [1, 2, 3,5,5];
let arr2 = arr1.slice(0);
console.log(arr2);
3.concat
let arr1 = [1,2,3,5,5];
let arr2 = arr1.concat();
console.log(arr2);
4.扩展运算符
let arr1 = [1,2,3];
let [...arr2] = arr1;
console.log(arr2);
5.Array.from
let arr1 = [1,2,3];
let arr2 = Array.from(arr1);
console.log(arr2);
对象3种拷贝
1.for…in…循环
2.利用JSON
var obj = {name:'小花'}
var obj1 = JSON.parse(JSON.stringify(obj))
3.扩展运算符
var obj = {name:'小花',age:13};
var obj1 = {...obj}