深拷贝/深克隆

深拷贝/深克隆(deepclone)

一. JSON.stringify 和 JSON.parse0

1
2
3
function deepCopy(obj){
return JSON.parse(JSON.stringify(obj));
}

局限性:

  • 无法实现对undefined、函数(function)、正则表达式(RegExp)、Symbol类型的克隆
  • 会抛弃对象的构造函数(constructor),所有的构造函数会指向Object
  • 对象有循环引用,会报错

二. 遍历

1
2
3
4
5
6
7
8
9
10
11
12
function deepCopy(obj){
// 判断是否是简单数据类型
if(typeof obj == "object"){
var result = obj.constructor == Array ? [] : {};
for(let i in obj){
result[i] = typeof obj[i] == "object" ? deepCopy(obj[i]) : obj[i];
}
} else {
var result = obj;
}
return result;
}

本博客所有文章除特别声明外,均采用 CC BY-SA 3.0协议 。转载请注明出处!