1.使用JSON.parse(Json.stringify())实现深拷贝有哪些坑?
- 如果属性值是undefined、或者函数,序列化后属性丢失;
- 如果属性值是RegExp、Error对象,序列化后值是{};
- 如果属性值是NaN、Infinity和-Infinity,则序列化的结果会变成null
2. 实现:
function deepClone(obj) { if (obj === null || typeof obj !=='object') 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."); }
注:Symbol是基础类型(值类型)