js深拷贝实现
使用json.stringify实现深拷贝有哪些坑。
这篇总结得比较好了
实现:
function deepClone(obj) { if (null == obj || "object" != typeof obj) return obj; if (obj instanceof Array) { var copy = []; for (var i = 0, len = obj.length; i < len; i++) { copy[i] = deepClone(obj[i]); } return copy; } if (obj instanceof Date) { var copy = new Date(); copy.setTime(obj.getTime()); return copy; } if(obj instanceof RegExp){ return new RegExp(obj); } if (obj instanceof Object) { var copy = {}; for (var attr in obj) { if (obj.hasOwnProperty(attr)) copy[attr] = deepClone(obj[attr]); } return copy; } throw new Error("Unable to copy obj this object."); }