Reputation: 11
Consider the following code snippet:
var arr1 = "john".split('');
console.log(arr1); // [ 'j', 'o', 'h', 'n' ]
var arr2 = arr1.reverse();
console.log(arr1); // [ 'n', 'h', 'o', 'j' ]
var arr3 = "jones".split('');
arr2.push(arr3);
console.log(arr1); // [ 'n', 'h', 'o', 'j', [ 'j', 'o', 'n', 'e', 's' ] ]
In the last console.log
, why does pushing to arr2
affect arr1
? Why does arr1
change when it's not modified, only arr2
is modified?
Upvotes: 0
Views: 374
Reputation: 343
There are two modifications to arr1
taking place on your code.
var arr2 = arr1.reverse();
The function Array.prototype.reverse() reverses an array in place. This means that arr1
will be reversed itself.
Also, when assigning objects, you are only passing a reference to them, so arr2
is actually arr1
(reversed) after this line.
arr2.push(arr3);
Because you assigned arr2
as a reference to arr1
, in this line you are actually modifying arr1
, being equivalent to writing arr1.push(arr3)
.
To create a new object from an array, you can use the function Array.prototype.slice(), since this method returns a copy of an array.
var arr1 = "john".split('');
console.log(arr1); // [ 'j', 'o', 'h', 'n' ]
var arr2 = arr1.slice().reverse();
console.log(arr1); // [ 'j', 'o', 'h', 'n' ]
var arr3 = "jones".split('');
arr2.push(arr3);
console.log(arr1); // [ 'j', 'o', 'h', 'n' ]
Upvotes: 1
Reputation: 2429
The reverse()
method in JavaScript mutates the array. This means that it changes the data in place—in the arr1
variable—and then returns a reference to that array. So arr2
is just a reference to arr1
, rather than a new set of data.
If you want completely new data, you can do as they say in this StackOverflow question:
var arr2 = arr1.slice().reverse();
That will slice
a new set of data and then reverse it, hence returning a new array instead of a reference to the first array.
Example:
var array = ['a', 'b', 'c', 'd', 'e'];
var notmutated = array.slice();
console.log('not mutated:', notmutated);
var mutated = array.reverse();
console.log('mutated: ', array);
Upvotes: 2
Reputation: 898
var arr1 = "john".split('');
console.log(arr1); // [ 'j', 'o', 'h', 'n' ]
var arr2 = arr1.slice().reverse();
console.log(arr2); // [ 'n', 'h', 'o', 'j' ]
var arr3 = "jones".split('');
arr2.push(arr3);
console.log(arr1); // [ 'j', 'o', 'h', 'n' ]
console.log(arr2); // [ 'n', 'h', 'o', 'j', ['j','o','n','e','s'] ]
Use slice() function to make a copy of your array.
References:
Upvotes: -1