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

What is the difference between deep copy and shallow copy in JS?

Guanhui
Release: 2020-06-12 14:47:10
Original
5384 people have browsed it

What is the difference between deep copy and shallow copy in JS?

#What is the difference between deep copy and shallow copy in JS?

The difference between the two is whether the copied entity of an object is actually obtained, rather than a reference. Deep copy opens up a memory address in the computer for storing the copied object, while shallow copy only It points to the copied memory address. If the object in the original address is changed, the shallow copied object will also change accordingly.

Deep copy

The simplest method is

JSON.parse(JSON.stringify())
function deepCopy(o) {
    return JSON.parse(JSON.stringify(o))
}
var c = {
    age: 1,
    name: undefined,
    sex: null,
    tel: /^1[34578]\d{9}$/,
    say: () => {
        console.log('hahha')
    }
}
// { age: 1, sex: null, tel: {} }
Copy after login

It should be noted that this copy method cannot copy some special files Properties (such as regular expressions, undefine, function)

Use recursion to copy all hierarchical properties

function deepCopyTwo(obj) {
    let objClone = Array.isArray(obj) ? [] : {};
    if (obj && typeof obj == 'object') {
        for (const key in obj) {
            //判断obj子元素是否为对象,如果是,递归复制
            if (obj[key] && typeof obj[key] === "object") {
                objClone[key] = deepCopyTwo(obj[key]);
            } else {
                //如果不是,简单复制
                objClone[key] = obj[key];
            }
        }
    }
    return objClone;
}
Copy after login

Shallow copy

object.assign(target,source)
Copy after login

Object The .assign method only copies enumerable properties in the source object and the properties of the object itself

If a property in the target object has the same key, the property will be overwritten by the property in the source. Properties of later sources will similarly override earlier properties.

Object.assign will skip those whose value is [null] null is a JavaScript literal that represents null or an "empty" value. That is, no object value is present. It is one of the JavaScript primitive values. ") or undefined source object.

Recommended tutorial: "JS Tutorial"



##

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

Related labels:
js
source:php.cn
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