var obj = {
a:'hello',
b:{
a:'world',
b:111
},
c:[11,'jack','Tom']
}
是从慕课网一门叫直面JavaScript中的30个疑难杂症的视频里看到的特此记录下
浅拷贝:
//方法1
function simpleClone(objNew){
var obj = {}
for(var i in objNew){
obj[i]=objNew[i]
}
return obj
}
var objCopy = simpleClone(obj)
objCopy.b.a = 'NOhello'
console.log(objCopy)
console.log(obj)
//方法2
var objCopy = Object.create(obj)
objCopy.b.a = 'NOhello'
console.log(objCopy)
console.log(obj)
深拷贝:
//方法1
function deepClone(startObj,endobj){
var obj = endobj || {}
for(var i in startObj){
if(typeof startObj[i]==='object'){
obj[i]= startObj[i].constructor===Array?[]:{}// 再次判断其构造函数是数组的构造函数还是对象的构造函数
deepClone(startObj[i],obj[i])
}else{
obj[i]=startObj[i]
}
}
return obj
}
var objCopy = deepClone(obj)
objCopy.b.a = 'NOhello'
console.log(objCopy)
console.log(obj)
//方法2
JSON.parse,JSON.stringify
var objCopy = JSON.parse(JSON.stringify(obj))
object->string
objCopy.b.a = 'NOhello'
console.log(objCopy)
console.log(obj)