1、var的缺点
声明提升、没有局部作用域、声明覆盖
2、深拷贝和浅拷贝
深拷贝:不影响 浅拷贝:影响
(1)var a = 1; var a = b = 1; 赋值,算深拷贝
(2)对象和数组是浅拷贝
(3)解构赋值 对于一维是深拷贝,多维是浅拷贝
//深拷贝
//深拷贝
var arr1 = [1,2,3];
var arr2 = [...arr1];
arr2.push(4);
//浅拷贝
var arr3 = [[1,2,3],[4,5,6]];
var arr4 = [...arr3];
arr4[0].push(7);
(4)变成深拷贝(不能拷贝方法function)
var arr = [
{name:"1",age:1},
{name:"2",age:2},
]
// var arr2 = arr;
var arr2 = JSON.parse(JSON.stringify(arr));
arr2.push({name:"3",age:3});
console.log(arr,arr2)
(5)标准的深拷贝=>引用数据类型(数组、对象)
function deepClone(source){
const targetObj = source.constructor === Array ? [] : {} ;
for(let keys in source){
if(source[keys] && typeof source[keys] === 'object'){
// targetObj[keys] = source.constructor === Array ? [] : {} ;
targetObj[keys] = deepClone(source[keys])
}else{
targetObj[keys] = source[keys]
}
}
return targetObj;
}