Javascript对象深度复制
本文基于ES5和ES6两个版本的Javascript,分别实现了对象的深度复制。对于不在Javascript对象原型链上的内容,将全部复制到新的对象中。
ES5的实现
function deepClone(source,target){
var _tar = target || {};
for(var key in source){
if(source.hasOwnProperty(key) && source[key] != null){
if(typeof source[key] === "object"){
_tar[key] = (Object.prototype.toString.call(source[key]) === "[object Array]")
? [] : {};
deepClone(source[key],_tar[key]);
}else{
_tar[key] = source[key];
}
}
}
return _tar;
}
- for in 循环会将对象原型链上的内容一并遍历到,因此使用hasOwnProperty方法进行过滤。
- Object.prototype.toString.call(source[key]) === “[object Array]” 判断当前对象是否是数组,注意该方法是唯一判断数组的准确方法。
ES6的实现
function deepCloneEs6(source,target){
var _tar = target || {};
for(var key of Reflect.ownKeys(source)){
if(typeof source[key] === "object"){
_tar[key] = (Array.isArray(source[key])) ? Array.of() : Object.create({});
deepClone(source[key],_tar[key]);
}else{
_tar[key] = source[key];
}
}
return _tar;
}
- Reflect.ownKeys(source) 可以直接忽略原型链上的内容
- Array.isArray是ES6新提供的方法,该方法其实封装了Object.prototype.toString.call(source[key]) === “[object Array]” 代码 。