两种javascript深拷贝的方法 发表于 2015-08-12 | 分类于 前端 , javascript | | 阅读次数 两种javascript深拷贝的方法 递归12345678910111213141516171819202122function deepCopy(obj) { if (!obj || typeof obj !== 'object') return obj; var target = isPlainObject(obj) ? {} : [], property, val; for (var key in obj) { val = obj[key]; // 防止循环引用 if (val === obj) continue; if (Array.isArray(val) || isPlainObject(val)) { target[key] = deepCopy(val); } else { target[key] = val; } } return target;}function isPlainObject(o) { return Object.prototype.toString.call(o) === "[object Object]";} 非递归123456789101112131415161718192021222324252627282930313233function deepCopy(obj) { if (!obj || typeof obj !== 'object') return obj; var target = isPlainObject(obj) ? {} : [], auxlity = [ [target, obj] ]; while (auxlity.length) { var item = auxlity.shift(), to = item[0], from = item[1]; for (var key in from) { var prop = from[key]; // 防止循环引用 if (from === prop) continue; if (Array.isArray(prop)) { to[key] = []; auxlity.push([to[key], prop]); } else if (isPlainObject(prop)) { to[key] = {}; auxlity.push([to[key], prop]); } else { to[key] = prop; } } } return target;}function isPlainObject(o) { return Object.prototype.toString.call(o) === "[object Object]";}