js deep copy and shallow copy

1. About javascript data types:

 5 basic data types (null, undefined, string, number, Boolean) + 1 object data type (object, Array)

 Among them, basic data types are passed by value, and object types (also called reference types) are passed by reference

2. Pass by value

For example, in the following example, I make num2 = num1, changing the value of num2 will not affect num1


Data type is pass by value

2. Pass by reference

For example, in the following example, I assign obj2 to obj1. When I change the value of obj2, the values ​​of obj1 and obj2 will change at the same time


In fact, obj2 = obj1, we just assign the reference address of obj1 to obj2, and they point to the same entity. This situation is actually what we call a shallow copy.

Shallow copy: The essence is to copy the reference address. The value of the reference data type is stored in the heap memory. Copying a complex type to another complex type is essentially copying the pointer address. Therefore, the copied objects point to the same entity, and their operations with each other will be different. affected.

Note: Object.assign is a shallow copy

3. Deep copy

Object deep copy: The essence of object deep copy is to create an empty object B, traverse the A object, and assign each attribute of A to B during the traversal process.

const source = { /* object A */
	name: 'test',
	age: '11'
}
let target = {} /* object B */
let deepCopy = (source) => { /* deep copy */
	for(let i in source) {                
	    if(typeof source[i] === 'object') {
	        target[i] = deepCopy(source[i])
	    } else {
	        target[i] = source[i]
	    }
	}
	return target
}

Let's test it in the browser console:


Changing the value of target does not affect the value of source

Array deep copy: We can use es6 and array methods to implement deep data copy (slice, concat, [...])

const source = [1, 2, 3, 4, 5]
let target1 = source.slice()
let target2 = source.concat()
let target3 = [...source]

Hit it in your browser and see

We can see that changing the value of target does not affect source

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324849138&siteId=291194637