//对象浅拷贝,不处理对象中的引用值
var p={
name:'张三',
age:18,
height:180
}
var p2={};
for(var key in p){
if(p.hasOwnProperty(key)){
p2[key] = p[key]
}
}
p2.name='李四';
console.log(p); //{name: "张三", age: 18, height: 180}
console.log(p2); //{name: "李四", age: 18, height: 180}
//深拷贝
function deepClone(obj){
let objClone = Array.isArray(obj)?[]:{};
if(obj && typeof obj==="object"){
for(key in obj){
if(obj.hasOwnProperty(key)){
//判断ojb子元素是否为对象,如果是,递归复制
if(obj[key]&&typeof obj[key] ==="object"){
objClone[key] = deepClone(obj[key]);
}else{
//如果不是,简单复制
objClone[key] = obj[key];
}
}
}
}
return objClone;
}
let a=[1,2,3,4],
b=deepClone(a);
a[0]=2;
console.log(a,b);
// JSON转换
var p1={
name:'张三',
age:18,
hobby:{
one:'coding',
two:'play'
}
}
var str=JSON.stringify(p1);
var p2=JSON.parse(str);
p2.hobby.three='shopping'
console.log(p1)
console.log(p2)