最近做个微信小程序,发现需要深度复制数组和字典,于是写了这个 Javascript 代码,可能考虑欠佳,欢迎增加及修订:
deepCopy: function (source) {// tyopeof ref: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/typeofvar _this = this//看看是否独立变量if (source) {if (typeof source === ‘string’) return sourceelse if (typeof source === ‘boolean’) return sourceelse if (typeof source === ‘number’) return source//else if (typeof source === ‘object’) return null}else {if (typeof source === ‘undefined’) retur nnullelse if (typeof source === ‘string’) return ”else if (typeof source === ‘boolean’) return falseelse if (typeof source === ‘number’) return 0else 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] = falseelse if (typeof source[key] === ‘number’) result[key] = 0else if (typeof source[key] === ‘object’) result[key] = null}}}return result}