1. JSON.parse(JSON.stringify()) 常用推荐!
let a = {
name: 'JJ',
age: 18
}
b = JSON.parse(JSON.stringify(a))
b.age = 25;
console.log(a, b);
2.迭代递归方法
export function deepCopy(obj) {
let result = Array.isArray(obj) ? [] : {};
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
if (typeof obj[key] === 'object' && obj[key] !== null) {
result[key] = deepCopy(obj[key]);
} else {
result[key] = obj[key];
}
}
}
return result;
}
3.lodash工具库
npm i --save lodash
--------------------
import _ from 'lodash'
使用:
const b=_.cloneDeep(a)