I have two arrays:
var array1 = [1, 2, 3];
var array2 = [4, 5, 6];
I want array 1 to be exactly equal to array 2. I've been told I can't simply do:
array1 = array2;
If I can't do this, how can I make array1 equal to array2?
Thanks
Set an Array Equal to Another Array in Java Using the copyOf() Method. The copyOf() method copies the content of an array and returns a new array.
Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. In other words, two arrays are equal if they contain the same elements in the same order. Also, two array references are considered equal if both are null.
To append values of an array into another array, you can call the push() method of the Array object.
ALGORITHM: STEP 1: Declare and initialize an array. STEP 2: Declare another array of the same size as of the first one. STEP 3: Loop through the first array from 0 to length of the array and copy an element from the first array to the second array that is arr1[i] = arr2[i].
If you just need a copy of the elements of an array you can simply use slice like this:
a = [1,2,3]
copyArray = a.slice(0)
[1 , 2 , 3]
As for why you should not use assignement here look at this example:
a = [1,2,3]
b = a
a.push(99)
a
[1,2,3,99]
b
[1,2,3,99]
If you copy an array you don't have this problem:
a = [1,2,3]
b = a.slice(0)
a.push(888)
a
[1,2,3,888]
b
[1,2,3]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With