- 递归循环
function deepClone(obj) {
if(obj === null) return obj
if( obj instance Date) return new Date(obj)
if( obj instance RegExp) return new RegExp(obj)
let objClone = Array.isArray(obj)?[]:{}
if(obj && typeof obj === 'object') {
for ( key in obj) {
if( obj.hasownProperty(key)) {
if( obj[key] && typeof obj[key] === 'object') {
objClone[key] = deepClone[key]
}else{
objClone[key] = obj[key]
}
}
}
}
retuen objClone
}
- JSON
var objClone = JSON.parse(JSON.stringify(sourceObj))
- jquery.extend()
var objClone = $.extend(true, targetObj, sourceObj)
- lodash-> _.deepClone()
var _ = require('lodash')
var sourceObj = {
name: 'xu'
}
var objClone = _.deepClone(sourceObj)