数组复制
栗子
1、直接赋值的数组拷贝方式,改变b时,会改变到原来的a数组
let a = [1,2,3];
let b = a;
b = [1,2]
//console.log(a) [1,2]
//console.log(b) [1,2]
2、由方法得到的数组,在外部被获得后(b获得a),b改变时,a也会被改变;
private getA(): number[] {
let a = [1,3,5];
return a;
}
private change(): void {
let b = this.getA();
b = [1,2]
}
//console.log(a) [1,2]
//console.log(b) [1,2]
避免方法:深度拷贝(深度复制)
1、遍历
let a: number[] = [1,2,3,4,5];
let b: number[] = new Array(a.length)
for(let i = 0;i < a.length; i++){
b[i] = a[i];
}
2、slice方法
let a: number[] = [1,2,3,4,5];
let b: number[] = a.slice(0);
3、[…a]方法
let a: number[] = [1,2,3,4,5];
let b: number[] = [...a];
4、concat()方法
let a = [1,2,3]
let b = a.concat([])
5、JSON对象的stringify和parse方法
let a = [1,2,3]
let b = JSON.parse(JSON.stringify(a));
6、递归
private deep(obj):void {
//判断拷贝的要进行深拷贝的是数组还是对象,是数组的话进行数组拷贝,对象的话进行对象拷贝
let objClone = Array.isArray(obj) ? [] : {};
//进行深拷贝的不能为空,并且是对象或者是
if (obj && typeof obj === "object") {
for (key in obj) {
if (obj.hasOwnProperty(key)) {
if (obj[key] && typeof obj[key] === "object") {
objClone[key] = deep(obj[key]);
} else {
objClone[key] = obj[key];
}
}
}
}
return objClone;
}