Javascript 微信小程序 js 如何深度复制数组或字典

最近做个微信小程序,发现需要深度复制数组和字典,于是写了这个 Javascript 代码,可能考虑欠佳,欢迎增加及修订:

deepCopy: function (source) {
// tyopeof ref: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/typeof
var _this = this
//看看是否独立变量
if (source) {
if (typeof source === ‘string’) return source
else if (typeof source === ‘boolean’) return source
else if (typeof source === ‘number’) return source
//else if (typeof source === ‘object’) return null
}
else {
if (typeof source === ‘undefined’) retur nnull
else if (typeof source === ‘string’) return ”
else if (typeof source === ‘boolean’) return false
else if (typeof source === ‘number’) return 0
else if (typeof source === ‘object’) return null
}
//处理对象:数组,字典等等
var result
//确定源是数组,还是字典
if (source.length && (typeof source.length === ‘number’)) {
//数组
result = []
for(var i=0; i< source.length; i++) {
result.push(_this.deepCopy(source[i]))
}
}
else if (typeof source.length === ‘undefined’) {
//字典
result = {}
for (var key in source) {
if (source[key]) {
result[key] = typeof source[key] === ‘object’ ? _this.deepCopy(source[key]) : source[key]
}
else {
if (typeof source[key] === ‘string’) result[key] = ”
else if (typeof source[key] === ‘boolean’) result[key] = false
else if (typeof source[key] === ‘number’) result[key] = 0
else if (typeof source[key] === ‘object’) result[key] = null
}
}
}
return result
}