Therefore, if you want to create an object with the same content as an existing object, you cannot do it through a simple assignment operation. This may still be unclear.
Look at the example below:
var a=[1,2,3,4]; var b=a;c=b; a.pop(); //Remove the last element alert(b); //Pop 1,2,3 alert(c ); //Pop 1,2,3
var a=[1,2,3,4]; var b=a;c=b; a.pop(); //Remove the last element alert( b); //Pop up 1,2,3 alert(c); //Pop up 1,2,3
We executed the above code and found that after the content of a was changed, the variable b The results of and c also changed.
The above situation may not be what we need. What we want is to create a "new" object with the same content as the original object. In this way we need to achieve it through some cloning methods.
Array is also a kind of Object in JS. Here we mainly summarize the cloning method of Array. Here we extend a clone method for the Array native object.
1. The simplest way is to create a new array and traverse the array and add items to the new array one by one.
Array.prototype.clone=function(){ var a =[]; for(var i=0,l=this.length;iArray.prototype.clone=function(){ var a=[]; for(var i=0,l=this.length;i
This kind of The implementation method is the easiest to think of and understand, but the code is a bit complicated. Let's carefully study some methods of Array. In fact, there is a very simple method. Let’s talk about the other two methods.
2. Through the slice method of Array object.
The slice method returns a segment of the array through the passed in values of parameters start and end. This method does not operate on the original array. We can use slice(0) to make it return all items.
Array.prototype.clone=function(){ return this .slice(0); }
Array.prototype.clone=function(){ return this.slice(0); }
3. Through the concat method of the Array object.
The concat method is used to merge arrays. By merging with an empty function, our cloning function can be realized.
Array.prototype.clone=function(){ return [ ].concat(this); } //or Array.prototype.clone=function(){ return this.concat(); }
Array.prototype.clone=function(){ return [].concat(this) ; } //Or Array.prototype.clone=function(){ return this.concat(); }
If you use your imagination, there should be other ways. The above are just the two methods I thought of. .
The simplest way to clone an array in JavaScript
Fast cloning of JavaScript arrays (slice() function) and sorting, shuffling and searching of arrays (sort ()function)