明天小编和大家一起探讨js中深拷贝和浅拷贝,简略一点了解就是,对于援用数据类型,深拷贝是数据援用地址不同,在扭转一个数据的时候,不会影响另一个数据。而浅拷贝刚好相同。两个数据援用的是同一个堆内存地址,一个数据扭转的时候,会影响另一个相干的数据。
在之前的章节中,小编提起过对于对象的复制的办法,Object.assign(),然而这个办法只是针对对象的浅拷贝。大家也能够关注我的微信公众号,蜗牛全栈。
let target = {}let source = { a:1, b:2}Object.assign(target,source)console.log(target) // {a:1,b:2}let target = {}let source = { a:{ b:{ c:1 } }, e:2, f:3}Object.assign(target,source)console.log(target) // {a:{b:{c:1}},e:2,f:3}
let target = { a:{ b:{ c:1 } }, e:4, f:5, g:6}let source = { a:{ b:{ c:1 } }, e:2, f:3}Object.assign(target,source)console.log(target) // {a:{b:{c:1}},e:2,f:3} // 这外面没有将target中的g属性和值
深拷贝(根本数据类型)
let a = 5let b = aa = 6console.log(a,b) // 6 5
浅拷贝(对象,两个数据相互影响。一个数据内容扭转之后会影响另一个数据)
let obj1 = { name:"lilei", age:18}let obj2 = obj1console.log(obj1) // {name:"lilei",age:18}console.log(obj2) // {name:"lilei",age:18}obj1.age = 30console.log(obj1) // {name:"lilei",age:30}console.log(obj2) // {name:"lilei",age:30}
深拷贝(对象)
形式一:
let obj1 = { name:"lilei", age:18}let str = JSON.stringify(obj1)let obj2 = JSON.parse(str)console.log(obj1) // {name:"lilei",age:18}console.log(obj2) // {name:"lilei",age:18}obj1.age = 30console.log(obj1) // {name:"lilei",age:30}console.log(obj2) // {name:"lilei",age:18}
形式二:
// 判断数据类型let checkType = data => { let t = Object.prototype.toString.call(data).slice(8,-1) return t}// 只思考对象和数组还有根本数据类型的深拷贝let deepClone = target => { let targetType = checkType(target) let result if(targetType === "Object"){ result = {} }else if(targetType === "Array"){ result = [] }else{ return target } for(let i in target){ let value = target[i] // 每个属性对应的值 // 兼容援用数据类型中还存在援用数据类型的状况 let valueType = checkType(value) if(valueType === "Object" || valueType === "Array"){ result[i] = deepClone(value) // 递归 }else{ result[i] = value } } return result}
附加:
一、JSON:JSON实质就是字符串,对象键不必引号,JSON须要用引号
JSON.stringify(obj) // 将对象转换成JSON格局字符串JSON.parse(obj) // 将JSON字符串转换成对象
二、typeof只能判断根本数据类型,不能判断援用数据类型,比方对象和数组,返回的都是Object。能够用以下形式解决
let checkType = data => { let t = Object.prototype.toString.call(data) // 已经在面试的时候,被问过这个问题,心愿小伙伴也能够把这个写到本人的小本本上,好能更好的应酬面试官 // let t = Object.prototype.toString.call(data).slice(8,-1) 截取对应数据类型,比方Object和Array console.log(t)}checkType({}) // [Object Object]checkType([]) // [Object Array]