Home > Web Front-end > JS Tutorial > body text

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

王林
Release: 2020-05-10 09:14:11
forward
3335 people have browsed it

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
}
Copy after login

Shallow copy example code:

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

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!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!