在深拷贝递归的时候需要考虑循环应用,可以通过判断一个对象的字段有没有引用这个对象或者任意父级来实现。
var testObject = { 'name': ‘John', 'age': 24, 'testArray': [3, 2, 4, 5], 'testObject': { 'attr1': 'value1', 'attr2': 321, 'attr3': [1, 2, 3] } } // 测试循环引用 testObject['testCircularReference'] = testObject function deepClone(source, parentObject) { if (!parentObject) { parentObject = [] } if (typeof source !== 'object') { return source } if (parentObject.indexOf(source) >= 0) { throw new Error('circular reference') } else { parentObject.push(source) } var targetObject = source.constructor === Array ? [] : {} for (var key in source) { if (source.hasOwnProperty(key)) { if (typeof source[key] !== 'object') { targetObject[key] = source[key] } else { targetObject[key] = deepClone(source[key], parentObject) } } } return targetObject } var newObject = deepClone(testObject) console.log(newObject.testObject === testObject.testObject)