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

js implements deep and shallow copy method

小云云
Release: 2018-03-16 16:44:02
Original
2654 people have browsed it

Speaking of deep and shallow copying, I think we need to clarify value types and reference types. This article mainly shares with you the js implementation of deep and shallow copying methods, hoping to help everyone.

Value type

The so-called value type is undefined, null, number , string, boolean and other five basic data types, there should also be a Symbol type.

Value type data is stored in stack memory

Modifying the value in value type is equivalent to opening a new one in stack memory The storage space is similar to:

js implements deep and shallow copy method

Explained in code:

var num1 = 5var num2 = num1
Copy after login

The value of the value type cannot be changed

There is a fundamental difference between primitive values ​​(undefined, null, Boolean values, numbers and strings) and objects (including arrays and functions) in JavaScript. Primitive values ​​are immutable: no method can change (or "mute") a primitive value. This is obviously true for numbers and booleans - changing the value of a number itself doesn't make sense, but it's less obvious for strings, because strings look like arrays of characters and we expect to be able to specify the index by to modify characters in a string. In fact, javascript prohibits this. All methods in string appear to return a modified string, but actually return a new string value.

var str = 'abc'str[0] = 'd'console.log(str)  // 'abc'
Copy after login

The comparison of value types is the comparison of values
The comparison of value types is the comparison of values. As long as their values ​​are equal, they are considered equal

var a = 1;var b = 1;console.log(a === b);//true
Copy after login

Reference type

Reference type data is stored in heap memory
Reference type value is stored in heap memory, and the variable stores a value stored in stack memory , a pointer to heap memory.

var person1 = {name:'jozo'};var person2 = {name:'xiaom'};var person3 = {name:'xiaoq'};
Copy after login

js implements deep and shallow copy method

The value of a reference type can be changed
The reference type can directly change its value

 var a = [1,2,3];
 a[1] = 5;
 console.log(a[1]); // 5
Copy after login

The comparison of reference types is the comparison of references
So every time we operate on the reference type in js, we operate on the reference of its object (the pointer saved in the stack memory), so compare the two The reference type depends on whether its references point to the same object.

var a = [1,2,3];var b = [1,2,3];console.log(a === b); // falsevar a = [1, 2, 3]var b = aconsole.log(a === b)  // true
Copy after login

Passing by value and passing by address

After understanding the difference between basic data types and reference types, we should be able to understand the difference between passing by value and passing by address.
When we perform an assignment operation, the assignment (=) of the basic data type is to open a new stack memory in the memory, and then assign the value to the new stack

var a = 10;var b = a;

a ++ ;
console.log(a); // 11console.log(b); // 10
Copy after login

js implements deep and shallow copy method

So, the two variables assigned by the basic type are two independent variables that do not affect each other.

But the assignment of reference types is by address. Just change the pointer pointing, for example, that is to say, the assignment of the reference type is the assignment of the address of the object stored in the stack. In this case, the two variables point to the same object, so the operations between the two affect each other.

var a = {}; // a保存了一个空对象的实例var b = a;  // a和b都指向了这个空对象a.name = 'jozo';
console.log(a.name); // 'jozo'console.log(b.name); // 'jozo'b.age = 22;
console.log(b.age);// 22console.log(a.age);// 22console.log(a == b);// true
Copy after login

js implements deep and shallow copy method

Shallow copy

js implements deep and shallow copy method

##Implementation:

function shallowCopy (src) {
    let  new = {}    for (let i in src) {        if (src.hasOwnProperty(i)) {            new[i] = src[i]
        }
    }    return new}
Copy after login

Deep copy

One kind of cool operation is to use JSON.parse and JSON.stringify

var a = {
    name: 'SpawN',
    age: 28}var b = JSON.parse(JSON.stringify(a))
b.name = 'Johnny.R'console.log(a.name)  // 'SpawN'
Copy after login

The other is a professional operation, which is a regular operation, which is to use recursion to traverse all attributes under the target object

function deepCopy(obj) {
    if (typeof obj !== 'object') return
    // 初始化
    var newObj = obj instanceof Array ? [] : {}    for (let k in obj) {        if (obj.hasOweProperty(k)) {
            newObj[k] = typeof obj[k] === 'object' ? agruments.callee(obj[k]) : obj[k]
        }
    }    return newObj
}
Copy after login
This is only a basic deep copy, and some boundaries are not properly handled. The basic idea is to use the for in loop. When the value is an object, the for in loop is recursively performed.

Related recommendations:

Detailed explanation of deep and shallow copies of js arrays and objects

How to implement deep and shallow copies of arrays and objects

Introductory Tutorial on Deep and Shallow Copy: 10 Recommended Zero-Based Introductory Tutorials on Deep and Shallow Copy

The above is the detailed content of js implements deep and shallow copy method. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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