- 淺拷貝是創(chuàng)建一個新對象,這個對象有著原始對象屬性值的一份精確拷貝河闰。如果屬性是基本類型断楷,拷貝的就是基本類型的值锨匆,如果屬性是引用類型,拷貝的就是內存地址 冬筒,所以其中一個對象改變了這個地址恐锣,就會影響到另一個對象。
- 深拷貝是將一個對象從內存中完整的拷貝一份出來,從堆內存中開辟一個新的區(qū)域存放新對象,且修改新對象不會影響原對象舞痰。
創(chuàng)建一個對象栗子
var obj = {
heroName: '百里守約',
heroSkills:['瞄準', ['靜謐之眼', '狂風之息', '逃脫']]
}
復制
var copyObj = obj
copyObj.heroName = '百里玄策'
copyObj.heroSkills[0] = '狂熱序章'
console.log(obj) console.log(copyObj )
copyObj打印是
淺拷貝
function shallowCopy(obj){
let target = {}
for (const i in obj) {
if (obj.hasOwnProperty.call(obj, i)) {
target[i] = obj[i];
}
}
return target
}
var copyObj = shallowCopy(obj)
copyObj.heroName = '百里玄策'
copyObj.heroSkills[0] = '狂熱序章'
console.log('obj', obj) //打印是
console.log('copyObj', copyObj )
shallowCopy打印
深拷貝
function deepCopy(obj){
let deepCloneObj = {}
if(typeof obj !== 'object') return obj
for (const i in obj) {
if (obj.hasOwnProperty(i)) {
deepCloneObj[i] = deepCopy(obj[i]);
}
}
return deepCloneObj
}
var copyObj = deepCopy(obj)
copyObj.heroName = '百里玄策'
copyObj.heroSkills[0] = '狂熱序章'
console.log('obj', obj) //打印是
console.log('copyObj', copyObj )
deepCopy打印
深拷貝 更多類型判斷
var obj = {
heroName: '百里守約',
heroSkills:['瞄準', ['靜謐之眼', '狂風之息', '逃脫']],
date: new Date(),
reg: '\p+\/'
}
function deepCopy(obj){
let deepCloneObj = {}
if(typeof obj !== 'object') return obj
if(obj === null) return obj
if(obj instanceof Date) return new Date()
if(obj instanceof RegExp) return new RegExp()
for (const i in obj) {
if (obj.hasOwnProperty(i)) {
deepCloneObj[i] = deepCopy(obj[i]);
}
}
return deepCloneObj
}
var copyObj = deepCopy(obj)
copyObj.heroName = '百里玄策'
copyObj.heroSkills[0] = '狂熱序章'
console.log('obj', obj) //打印是
console.log('copyObj', copyObj )
淺拷貝有哪些
1.函數(shù)庫lodash的_.clone
方法
const _clone = require('lodash.clone')
2.Object.assign()
const original = {
name: 'Fiesta',
car: {
color: 'blue',
},
}
const copied = Object.assign({}, original)
original.name = 'Focus'
original.car.color = 'yellow'
copied.name //Fiesta
copied.car.color //yellow
3.展開運算符...
該價差運營商是一個ES6 / ES2015的特性土榴,能夠進行淺克隆,相當于什么非常方便地Object.assign()
做响牛。
const copied = { ...original }
4.Array.prototype.concat()
5.Array.prototype.slice()
深拷貝有哪些
1.JSON.parse(JSON.stringify())
let obj = {
a: new Date(),
b: NaN,
c: new Function(),
d: undefined,
e: function () {
return 1
},
f: Number,
g: false,
h: Infinity,
}
console.log(JSON.parse(JSON.stringify(obj))) //{a: "2020-12-02T03:06:19.959Z", b: null, g: false, h: null}
打隅枨荨(弊端 )僅當您沒有任何內部對象和函數(shù)赫段,而只有值時,這才起作用矢赁。
2.函數(shù)庫lodash的_.cloneDeep
方法
const clonedeep = require('lodash.clonedeep')