JavaScript深拷贝
Feb 13, 2018
只针对Object类型的深拷贝,自己总结的三种方式,分别为:递归的方式、广度优先遍历的方式、使用JSON.parse()方法。
递归:
12345678910111213function copy(source) {var key, targetif (type(source) === "object") {target = {}for (key in source) {if (type(source[key]) === "array" || "object") {target[key] = copy(source[key])} else if (source[key] !== undefined) target[key] = source[key]}}return target}广度优先遍历
1234567891011121314151617181920function copy(data){var obj = {};var originQueue = [data];var copyQueue = [obj];while(originQueue.length > 0){var _data = originQueue.shift();var _obj = copyQueue.shift();for(var key in _data){var _value = _data[key]if(typeof _value !== 'object'){_obj[key] = _value;} else {originQueue.push(_value);_obj[key] = {};copyQueue.push(_obj[key]);}}}return obj;}JSON
1JSON.parse(JSON.stringify(source))
参考: http://blog.csdn.net/sysuzhyupeng/article/details/70340598