赋值的话基本数据类型都会相互影响,注意深浅拷贝和赋值的差别
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/6f59ee9cd6a661e53ed1dedc4f7c6a0e.png#pic_center)
浅拷贝,要实现基本数据类型,互不影响,而引用类型会互相同步影响
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/243e8d78d237e5a7b763d4d70e580255.png#pic_center)
定义的变量放在栈当中,引用类型放在堆当中
浅拷贝的方案
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/5bd2d2cb74bcf456c258963fdc765eaa.png#pic_center)
var qian={
z:1,
x:2,
y:3,
q:function(){console.log(1)},
r:[1,2,3],
t:{a:1,b:2}
}
function shallowCopy(obj){
var target={}
for(var i in obj){
if(obj.hasOwnProperty){
target[i]=obj[i]
}
}
return target
}
var p=shallowCopy(qian)
p.t.a=200
console.log("浅拷贝的结果",p)
console.log("函数原始内容",qian)
var qian1={
z:1,
x:2,
y:3,
q:function(){console.log(1)},
r:[1,2,3],
t:{a:1,b:2}
}
var cloneObj2={}
cloneObj2= Object.assign(cloneObj2,qian1)
console.log("es6方法","Object.assign(cloneObj2,obj)",cloneObj2)
cloneObj2.t.a=520
console.log("原始内容",qian1)
console.log("修改后520的数据",cloneObj2)
深拷贝的方案
var srouce={
a:1,
b:2,
c:3,
d:function(){console.log(1)},
e:[1,2],
f:{m:1,j:2,n:3}
}
var srouce1=JSON.parse(JSON.stringify(srouce))
console.log("srouce",srouce,"srouce1",srouce1)
srouce1.a=1000
console.log("srouce",srouce,"srouce1",srouce1)
var ddd={a:1,b:2,c:function(){console.log(1)},d:[0,1,2],e:{a:1,b:2,c:3}}
function JQ(Boolean,cloneOver,obj){
return $.extend(Boolean,cloneOver,obj)
}
console.log("ddd",ddd)
var xxxx=JQ({},ddd)
console.log("xxxx",xxxx)
xxxx.e.a=520
console.log("被浅克隆后",ddd)
var xxxx=JQ(true,{},ddd)
console.log("xxxx深拷贝",xxxx)
obj={
z:1,
x:2,
y:3
}
var cloneObj={}
for(var key in obj){
cloneObj[key]=obj[key]
console.log(cloneObj)
}
console.log("Object.getOwnPropertyNames(obj)",Object.getOwnPropertyNames(obj))
Object.getOwnPropertyNames(obj).forEach(function(item){
cloneObj[key]=obj[key]
})
console.log("es5方法",cloneObj)
var cloneObj1={}
console.log("Object.entries(obj)",Object.entries(obj))
for(var[key,value] of Object.entries(obj)){
cloneObj1[key]=value
}
console.log("es6方法",cloneObj1)