var obj = {a: 11, b: {c: 22, d: 33, e: {f: 44, g: {h: 55}}}}
var arr = [11, [22, 33, [44, [55]]]]
function copyObj(obj) {
var newObj = obj.constructor === Array ? [] : {};
for (var key in obj) {
if(obj.hasOwnProperty(key)) {
// 这里使用递归,属性类型为对象则进一步遍历
if (obj[key] && typeof obj[key] === 'object') {
newObj[key] = obj[key].constructor === Array ? [] : {};
newObj[key] = copyObj(obj[key])
} else {
newObj[key] = obj[key]
}
}
}
return newObj
}
附运行效果图
网友评论