Note: this isn’t one of the millions dups of the common array copy ‘problem’ where using arr.slice(0) fixes this ‘problem’
That said, I want to understand why I am getting this unexpected result:
var oldArr = [[1,2],[3,4]];
var find = oldArr[1];
var newArr = oldArr.slice(0);
console.log(newArr.indexOf(find)); //1?
//proof that newArr is NOT referenced to oldArr
newArr[0] = "Hi";
newArr[1] = "How are you?";
console.log(oldArr+" "+newArr); //"1,2,3,4 Hi,How are you?"
If you replace find with any of the following alternatives, it returns the expected -1:
- Use
[3,4]directly - Use a variable holding
[3,4] - Use a variable with reference of another array holding
[3,4]
I can’t find any explanation on why there is any difference between these last three methods and the first example. As far as I know, there shouldn’t be any.
Any ideas?
In:
There are three array objects created.
Only the outer one is being
slice‘d. This results in a “shallow copy”.Consider this:
Happy coding!