首先等你有空的时候可以看这篇,要用可以看我这篇
https://www.cnblogs.com/echolun/p/7889848.html
1.有一点需要明确的是 深拷贝只是针对引用数据类型来说的,基本数据类型都是深拷贝
基本数据类型有哪些,number,string,boolean,null,undefined,symbol六类。
引用数据类型(Object类)有常规名值对的无序对象{a:1},数组[1,2,3],以及函数
2.基本数据类型的浅拷贝就是一般赋值,
var a = 'jack' var b b = a console.log(b) //jack b = '你好' console.log(b)//你好 console.log(a) //jack
a并不会因为b的改变而改变,但是这是浅拷贝,不是深拷贝
3.接下来是引用数据类型深拷贝和浅拷贝
浅拷贝的作用:
主要是赋值,并且复制后的对象改变之前的对象也会改变
a. es6的Object.assign(obj)浅拷贝
var obj = { name: 'jack', age: 18 } var data = Object.assign(obj) console.log(data) //{name: 'jack',age: 18} data.name = '花花' console.log(data)//{name: "花花", age: 18} console.log(obj)//{name: "花花", age: 18}
b es6的解构赋值
let obj = { name: 'jack', age: 18 } let {age,name} = obj let data = { name,age} console.log(data) //{age:18} data.age = 20 console.log(data) //{age:20} console.log(obj) //{age:18}
c 循环赋值(知识点:for和forEach用来循环数组,for in 数组 对象都行)
var obj = { name: 'jack', age: 18 } var params = {} for(var key in obj){ params[key] = obj[key] } console.log(params, 22)//{name: "jack", age: 18}
或者
var obj = { name: 'jack', age: 18, hobby: { school: 'listen video', home: 'watch TV' } } var params = {} params =JSON.parse(JSON.stringify(obj))
深拷贝
为什么要用到深烤贝
下面有个🌰:
因为用框架是双向数据绑定的,所以赋值之后并不需要原始数据obj也跟着动,所以要深度clone来重新对数据做处理,而不要影响之前的数据
如果我用浅拷贝:
var obj = { name: 'jack', age: 18, hobby: { school: 'listen video', home: 'watch TV' } } var params = {} for(var key in obj){ params[key] = obj[key] } console.log(params,22) params.hobby.school = 'read books' console.log(params,11) console.log(obj,33)
并没有达到目的
用深拷贝
var obj = { name: 'jack', age: 18, hobby: { school: 'listen video', home: 'watch TV' } } var params = {} params = this.deepClone(obj) function deepClone(source) { if (!source || typeof source !== 'object') { throw new Error('error arguments', 'shallowClone'); } var targetObj = testArray(source) ? [] : {}; for (var keys in source) { if (source.hasOwnProperty(keys)) { if (source[keys] && typeof source[keys] === 'object') { targetObj[keys] = source[keys].constructor === Array ? [] : {}; targetObj[keys] = deepClone(source[keys]); } else { targetObj[keys] = source[keys]; } } } return targetObj } function testArray(obj) { return Object.prototype.toString.call(obj) === '[object Array]' } params.hobby.school = 'read books' console.log(params,11) console.log(obj,33)
打印结果:
下面是vue.js里面的实际应用
deepClone (source){ if (!source || typeof source !== 'object') { throw new Error('error arguments', 'shallowClone') } var targetObj = this.testArray(source) ? [] : {} for (var keys in source) { if (source.hasOwnProperty(keys)) { if (source[keys] && typeof source[keys] === 'object') { targetObj[keys] = source[keys].constructor === Array ? [] : {} targetObj[keys] = this.deepClone(source[keys]) } else { targetObj[keys] = source[keys] } } } return targetObj }, testArray(obj){ return Object.prototype.toString.call(obj) === '[object Array]' }
来源:https://www.cnblogs.com/antyhouse/p/10195172.html