深度克隆,递归所有属性, 一比一复制
function cloneDeep(objectVal) {
let newObj = Array.isArray(objectVal) ? [] : {}
function isValueType(value) {
let str = Object.prototype.toString.call(value);
return str.match(/\[object (.*?)\]/)[1].toLowerCase();
}
function clone(obj, item, key) {
for (let i in obj) {
if (['object', 'array'].includes(isValueType(obj[i]))) {
if (key) {
item[i] = Array.isArray(obj[i]) ? [] : {}
clone(obj[i], item[i], i)
} else {
newObj[i] = Array.isArray(obj[i]) ? [] : {}
clone(obj[i], newObj[i], i)
}
} else {
if (item) {
item[i] = obj[i]
} else {
newObj[i] = obj[i]
}
}
}
}
try {
clone(objectVal)
} catch (err) {
console.warn(err)
}
return newObj
}