var p = {
"id":"007",
"name":"刘德华",
"wife":{
"id":"008",
"name":"刘德的妻子",
"address":{
"city":"北京",
"area":"海淀区"
}
}
}
// json
function copyObj(obj){
let newObj = {}
for(let index in obj){
if(typeof obj[index] == 'object'){
newObj[index] = copyObj(obj[index])
}else{
newObj[index] = obj[index]
}
}
return newObj
}
// Array
var p1 = {
"id":"007",
"name":"刘德华",
"books":new Array("三国演义","红楼梦","水浒传")//这是引用类型
}
// 自我复制
Array.prototype.CopySelf = function(){
let arr = new Array()
for(let i in this){
arr[i] = this[i]
}
return arr
}
//数组
function copyObj1(obj){
let newObj = {}
for(let i in obj){
if(typeof obj[i] == 'object'){
newObj[i] = obj[i].CopySelf()
}else{
newObj[i] = obj[i]
}
}
return newObj
}
let a = copyObj(p)
p.name = "123"
p.wife.id=444
p.wife.address.city="上海"
console.log(p)
console.log(a)
// ------------------------------
let b = copyObj1(p1)
p1.name = '001'
p1.books[1] = 'qwe'
console.log(p1)
console.log(b)
console