Reversing the array remains in the original order
I am trying to modify an array in typescript. This is what the original array looks like:
But when I call reverse()
on the array, it doesn't change:
recommendations
- an array of arrays, declared like this:
recommendations: any;
And an instance:
me.recommendations = [[]];
Can anyone tell me why the array is not reversed and how to fix this problem?
thank
The problem is that [] .reverse () doesn't behave the way you expect.
reverse
changes of the value of the array, so the array is reversed, just you view both variables whatever
and yup
after it happened.
So the array changed and you just made 2 references to this object.
The array has been canceled. You fooled yourself in the debugger.
reverse
swaps the array in place and returns a reference to the array. In other words,
> var x = [1, 2, 3];
> var y = x.reverse();
> x
[3, 2, 1]
> y
[3, 2, 1]
> x === y
true