var source = {name:666};
source.o = source;
这里直接用JSON.stringify(source)打印会报错:Converting circular structure to JSON at Object.stringify,正常需要删除对象的循环引用,这种错误的编码方式,但是有时候我们想打印下对象里都有什么,所以就有了一下方式:
deepClone = function(source) {
if (!source || typeof source !== 'object') {
throw new Error('error arguments', 'shallowClone')
}
var targetObj = this.testArray(source) ? [] : {}
let iii = 0;
for (var keys in source) {
console.log('\r\n'+keys);
targetObj[keys] = source[keys];
if(iii >= 50 ){ //防止对象过多死循环 导致栈溢出
break;
}
iii++;
}
return targetObj
}
console.log(deepClone(source));
评论