# 最简单的实现
不足之处:JSON会过滤掉function、undefined、null
var newObj = JSON.parse(JSON.stringify(obj))
# deepClone
递归实现
function deepCoty(obj){
if(typeof obj == "object"){
var result = Array.isArray(obj) ? [] : {}
for(let i in obj){
result[i] = obj[i] == null ? null :
typeof obj[i] == "object" ? deepCoty(obj[i]) : obj[i]
}
}else{
var result = obj
}
return result
}
测试:
var obj = "test1"
var obj1 = [1,3,4,"5"]
var obj2 = {
string: "string--",
array: [1,2,3,{name: "xiaoming"}],
people: {
name: "xiaoming",
age: 11
},
no: null
}
console.log(deepCoty(obj))
console.log(deepCoty(obj1))
console.log(deepCoty(obj2))
← 原型链 JSON.parse()实现 →