使用for in 去遍历 对象会将prototype上面扩展的方法或者属性也打印出来
// 递归写法
Object.prototype.clone = function(){
let o = this.constructor === Array ? [] : {};
for(let e in this){
o[e] = typeof this[e] === "object" ? this[e].clone() : this[e];
}
return o;
}
let obj = {
a : 1,
b : {
c: 2
}
}
let obj2 = obj.clone();
console.log(obj2);// { a: 1, b: { c: 2, clone: [Function] }, clone: [Function] }
解决方法可以为每一次的遍历加上hasOwnProperty
hasOwnProperty具体的作用就是判断该属性是否属于对象自身的属性
// 递归写法
Object.prototype.clone = function(){
let o = this.constructor === Array ? [] : {};
for(let e in this){
if(this.hasOwnProperty(e)){
o[e] = typeof this[e] === "object" ? this[e].clone() : this[e];
}
}
return o;
}
let obj = {
a : 1,
b : {
c: 2
}
}
let obj2 = obj.clone();
console.log(obj2); // { a: 1, b: { c: 2 } }
也可以使用Object.keys()方式完成遍历操作
// 递归写法
Object.prototype.clone = function(){
let o = this.constructor === Array ? [] : {};
Object.keys(this).forEach(item => {
o[item] = typeof this[item] === "object" ? this[item].clone() : this[item]
})
return o;
}
let obj = {
a : 1,
b : {
c: 2
}
}
let obj2 = obj.clone();
console.log(obj2);// { a: 1, b: { c: 2 } }
小技巧:object对象没有length属性,可以通过Object.keys(person).length,来获取person的长度了。