Copy the values of an array
P粉002546490
2023-08-20 12:42:44
<p>When copying one array to another in JavaScript: </p>
<pre class="brush:php;toolbar:false;">var arr1 = ['a','b','c'];
var arr2 = arr1;
arr2.push('d'); // Now, arr1 = ['a','b','c','d']</pre>
<p>I realized that <code>arr2</code> was referencing the same array as <code>arr1</code>, not a new, independent array. How do I copy an array to get two separate arrays? </p>
In Javascript, deep copy technology depends on the elements in the array. Let's start here.
Three types of elements
Elements can be: literal values, literal structures or prototypes.
From these elements, we can create three types of arrays.
Deep copy technology depends on these three array types
Depending on the type of elements in the array, we can use various techniques to perform deep copies.
Deep copy technology
Benchmarks
https://www.measurethat.net/Benchmarks/Show/17502/0/deep-copy-comparison
Literal array (type 1)
You can use
[ ...myArray ]
,myArray.splice(0)
,myArray.slice()
andmyArray.concat()
Techniques for deep copying arrays containing only literal values (Boolean values, numbers, and strings); among them,slice()
has the highest performance in Chrome, and in Firefox, the spread operator. ..
has the highest performance.Literal value array (type 1) and literal structure array (type 2)
You can use
JSON.parse(JSON.stringify(myArray))
technology to deep copy literal values (Boolean values, numbers, strings) and literal structures (arrays, objects), but prototype objects cannot be copied.All arrays (type 1, type 2, type 3)
cloneDeep(myArray)
or jQuery'sextend(true, [], myArray)
technology To deep copy arrays of all types. Among them, Lodash'scloneDeep()
has the highest technical performance.cloneDeep()
, but higher thanextend(true )
.So answer this question...
question
Answer
Because
arr1
is an array containing literals (booleans, numbers, or strings), you can use any of the deep copy techniques discussed above, whereslice()
and The spread operators...
have the highest performance.use this: