“This is the 25th day of my participation in the First Challenge 2022. For details: First Challenge 2022”
Shallow copy
introduce
Shallow copy, as the name suggests, is to make a copy of something.
Shallow copy But why add a shallow, is because js basic type and reference type stored in different locations, when copying will appear different copy mode.
Shallow copy Copies the value of the base datatype if it is copied, and the memory address if it is a reference datatype.
Shallow copy
-
The basic types of JS are stored in stack memory
Data size is determined, stored by value, can be directly accessed, and the basic data type value is immutable.
let str = '123' str[1] = '4' console.log(str) console.log(str[1]) Copy the code
The result is:
'123' '2' Copy the code
You might be wondering, what if it’s Boolean or numeric?
It’s the same thing, but when we change it, that’s reassigning the variable, not changing the value of the underlying data type. For example,
let str = 123 let str2 = true str = true str2 = 123 console.log(str) console.log(str2) Copy the code
The result is:
true 123 Copy the code
-
But reference types are stored in heap memory
Data size is uncertain and should be allocated differently according to different situations.
Normally we would set a pointer to the data address and put the pointer into stack memory. We access the pointer variable to get data for the reference type
The classic is the following code
const a = [1.2.3] const b = [1.2.3] console.log(a === b) Copy the code
The result is false
const a = [1.2.3] const b = a b[0] = 2 console.log(a) console.log(b) console.log(a===b) Copy the code
The result is:
[ 2, 2, 3 ] [ 2, 2, 3 ] true Copy the code
-
Shallow copy
-
Object.assign()
Object copy in ES6 is a shallow copy mode
Usage: object. The assign (target, source_1,…)
const a = { a: 1.b: { bb: true}}const b = { c: 2.d: { dd: false}}Object.assign(a,b) console.log(a) console.log(b) b.c=3 b.d.dd = true console.log(a) console.log(b) Copy the code
The results for
{ a: 1.b: { bb: true }, c: 2.d: { dd: false}} {c: 2.d: { dd: false}} {a: 1.b: { bb: true }, c: 2.d: { dd: true}} {c: 3.d: { dd: true}}Copy the code
As you can see, this only copies the first layer and does not copy the second layer object.
-
Handwritten shallow copy
const shallowCopy = (object) = > {
// Only objects are copied
if(! object ||typeofobject ! = ='object') return
// Check whether it is an array or an object
let newObject = Array.isArray(object) ? [] : {}
// Walk through the object and determine if it is an object attribute
for (let key in object) {
if (object.hasOwnProperty(key)) {
newObject[key] = object[key]
}
}
return newObject
}
Copy the code
conclusion
Shallow copy For base data types, copies the value of the base data type
For reference data types, the memory address is copied