var deepObj = {
a: 1,
b: [2, 3],
c: {
d: 1
}
}
let newDeep = deepObj
function deepClone(obj) {
if (!obj && typeof obj !== 'Object') {
return new Error('不是一个对象')
} else {
let newobj = obj.constructor === Array ? [] : {}
Object.keys(obj).forEach(item => {
if (obj[item] && typeof obj[item] === 'object') {
newobj[item] = deepClone(obj[item])
} else {
newobj[item] = obj[item]
}
})
return newobj
}
}
let arr = [1, 2, 3]
let testObj = {
a: 1
}
/* typeof进行判断是=== 字符串object */
console.log('typeof', typeof testObj === 'object');
/* constructor进行区分是通过=== Array和Object类型而不是字符串 */
console.log(arr.constructor === Array);
console.log(testObj.constructor === Object, 111);
/* 数组的Object.keys()是获取下标 */
console.log(Object.keys(arr));
/* 浅拷贝 */
console.log(deepObj === newDeep);
/* 深拷贝 */
console.log(deepObj === deepClone(deepObj));
console.log(deepClone(deepObj));
主要是通过typeof来进行第一层筛选是否是对象,从而进行克隆,从constructor来进行区分是object还是array,还可以用isArray来进行判断,对于里面的嵌套则是运用递归的原理。
注:typeof==='object' 这个地方是进行类型或者说是字符串判断,而constuctor是指向原型对象而不是字符串。