let a = {
age: 1
}
let b = Object.assign({}, a)
a.age = 2
console.log(b.age) // 1
通过展开运算符 ... 来实现浅拷贝
let a = {
age: 1
}
let b = {...a}
a.age = 2
console.log(b.age) // 1
深拷贝
JSON.parse(JSON.stringify(object))
会忽略 undefined
会忽略 symbol
不能序列化函数
不能解决循环引用的对象,会报错抛出异常
let a = {
age: 1,
jobs: {
first: 'FE'
}
}
let b = JSON.parse(JSON.stringify(a))
a.jobs.first = 'native'
console.log(b.jobs.first) // FE
let a = {
age: undefined,
sex: Symbol('male'),
jobs: function() {},
name: 'yck'
}
let b = JSON.parse(JSON.stringify(a))
console.log(b) // {name: "yck"}
递归
function isObject(obj) {
//Object.prototype.toString.call(obj) === '[object Object]'要保留数组形式,用在这里并不合适
return typeof obj === 'object' && obj != null
}
function cloneDeep1(obj){
if(!isObject(obj)) return obj
var newObj = Array.isArray(obj)? [] : {}
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
newObj[key] = isObject(obj[key])? cloneDeep1(obj[key]) : obj[key]
}
}
return newObj
}
问题:递归方法最大的问题在于爆栈,当数据的层次很深是就会栈溢出,例如循环引用
var a = {
name: "muyiy",
a1: undefined,
a2: null,
a3: 123,
book: {title: "You Don't Know JS", price: "45"}
}
a.circleRef = a
// TypeError: Converting circular structure to JSON
JSON.parse(JSON.stringify(a))
//Uncaught RangeError: Maximum call stack size exceeded at Object.hasOwnProperty (<anonymous>)
cloneDeep1(a)
对象类型在赋值的过程中其实是复制了地址,从而会导致改变了一方其他也都被改变的情况 let a = { age: 1 } let b = a a.age = 2 console.log(b.age) // 2浅拷贝Object.assign : 拷贝所有的属性值到新的对象中,如果属性值是对象的话,拷贝的是地址,所以并不是深拷贝 let a = { age: 1 } let b = Object.ass