写法一:
//深拷贝 const deepCopy = (data) => { if (typeof data != ‘object‘ || data == null) return data let result = null if (data instanceof Array) { //Array的原型是Object result = [] } else { result = {} } for (let key in data) { const one = data[key] result[key] = deepCopy(one) } return result }
写法二:JSON.parse(JSON.stringify(data))
疑问:
既然有JSON.parse(JSON.stringify(data)),为啥还要用递归写深拷贝?
原因是如何data内有特殊的对象,例如Date类型的数据会被转成字符串,RegExp被转成{},Error被转成{}
let b = { g: ‘i am g‘, e: new Error(‘我是错误‘), exp:new RegExp(/ab+c/, ‘g‘), time: new Date() } let c = JSON.parse(JSON.stringify(b)) console.log(c.time instanceof String) //true console.log(c.exp) //{} console.log(c.e) //{}