repl.it : https://repl.it/BuXR/3
var str = "abc";
var str2 = str.split(" ").join("").split("");
var tmp = str2;
console.log(str2);
// => ['a','b','c']
console.log(tmp.reverse());
// => ['c','b','a']
console.log(str2);
// => ['c','b','a']
My question is why str2 is being changed even though it is not being reversed?
This is very upsetting to me, but I have a guess as to why this is happening. The tmp is just a pointer to the original str2, and when I call reverse() on tmp, it actually reverses str2.
Even if that really is what's happening, I still feel like it is a very counterintuitive way for a language to work.
The reverse() method reverses the order of the elements in an array. The reverse() method overwrites the original array.
The split() method splits a String object into an array of string by separating the string into sub strings. The reverse() method reverses an array in place. The first array element becomes the last and the last becomes the first.
prototype. reverse() The reverse() method reverses an array in place and returns the reference to the same array, the first array element now becoming the last, and the last array element becoming the first.
Your guess is right.
The tmp is just a pointer to the original str2, so whatever operations are performed on str2 it will be stored to memory and when you access tmp it find the reference to str2.
I have a guess as to why this is happening. The tmp is just a pointer to the original str2, and when I call reverse() on tmp, it actually reverses str2.
2 Reasons why this is happening:
reverse()
method reverses an array in place, hence tmp
is reversed: ref
tmp
and str2
are references to the same array instance, hence str2
also reversed.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