Home  >  Article  >  Web Front-end  >  What is the difference between deep copy and shallow copy of objects in js

What is the difference between deep copy and shallow copy of objects in js

王林
王林forward
2020-05-10 09:14:113302browse

What is the difference between deep copy and shallow copy of objects in js

#For basic data types, copying directly copies the value of the variable, while for reference types, what is actually copied is the address of the variable.

The distinction between shallow copy and deep copy is made on this basis. When copying this object, only the basic data type is copied, and only the reference data type is copied. The transfer of a reference without re-creating a new object is considered a shallow copy;

On the contrary, when copying the reference data type, a new object is created and its members are copied. variable, it is considered a deep copy.

Deep copy example code:

let o2 = JSON.parse(JSON.stringify(o1))
function deepCopy(s) {
const d = {}
for (let k in s) {
if (typeof s[k] == 'object') {
d[k] = deepCopy(s[k])
} else {
d[k] = s[k]
}
}
return d
}

Shallow copy example code:

let o2=Object.assign({},o1)

Recommended tutorial:js introductory tutorial

The above is the detailed content of What is the difference between deep copy and shallow copy of objects in js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete