This is the second day of my participation in the August More text Challenge. For details, see: August More Text Challenge
Deep copy and shallow copy
Deep copy and shallow copy is the front end of the interview must test point, it is necessary to make it clear, deep copy and shallow copy investigate its reason and memory has a great relationship, js basic data types are stored in the stack, reference types are saved in the memory heap, know this point can be very easy to understand deep copy and shallow copy. Without further ado, let’s get to the code
What is a deep copy and what is a shallow copy
A deep copy is when B copies a and b changes without affecting A, as follows
/ / copy
var a=3
var b=a
b=5
console.log(a,b)// the result is 3,5. This is a deep copy in some sense
/ / shallow copy
var a=[1.2.3]
var b=a
b[0] =4
console.log(a,b)// the result is [4,2,3], [4,2,3]. This is the shallow copy. The change in b also affects a
Copy the code
From the above, we can know that deep copy shallow copy often occurs in the object copy, the basic data type does not appear shallow copy problem, this is also said above and memory has a great relationship, below write how to achieve deep copy
Simple deep copy
var a= [1.2.3.4.5]
var b= []
a.forEach(function(val){
b.push(val)
})
b[0] =9
console.log(a,b)// results are [1,2,3,4,5],[9,2,3,4,5]
// This is a deep copy implemented with forEach, but not a full deep copy.
var a= [1[2.3].4.5]
var b= []
a.forEach(function(val){
b.push(val)
})
b[1] [0] =9
console.log(a,b)
// the result is [1,[9,3],4,5],[1,[9,3],4,5]
Copy the code
As you can see from the above code, the for loop does implement a simple deep copy, but there is a drawback, that is, for loop implementation of the deep copy can only copy one dimensional data, if there are multidimensional data will not be a deep copy effect.
More convenient and practical deep copy method
var a= [1[2.3].4.5]
var str = JSON.stringify(a)
var b = JSON.parse(str)
b[0] =6
b[1] [0] =7
console.log(a,b)
Copy the code
Here are the results:
This method is first converted to a string, which is the basic data type, by the json.stringify () method, and then to an array by the json.parse () method, both of which give us the deep copy we need. This method is adequate for use in daily work. However, there are also bad places, that is only the conversion of the array, the Internet has written JS, can achieve any data type of deep copy, and SO I study to complement.