1

I have a little problem with TypeScript. I want to reverse an Array. But before I reverse my Array, I want to write in into a local Storage.

The problem is, that I call the method to store the data before I call the method to reverse my array. But the stored data are already reversed.

Here is an example code and here is the Playground:

class TSRunner {

    defaultArray = []
    reversedArray = [];


    fillArray() {
        this.defaultArray = [1, 2, 3, 4, 5];
        this.reversedArray = this.defaultArray;
        console.log(this.reversedArray);
        this.reversedArray.reverse();
    }


}

let runner = new TSRunner();

runner.fillArray();

The output is already 5,4,3,2,1. But I want to get the 1,2,3,4,5 and after that, I want to reverse it. Maybe you could explain me this behaviour. I think it has something todo with the call by reference stuff. Thanks before ;)

Torben G
  • 750
  • 2
  • 11
  • 33
  • 2
    @CertainPerformance Why the `console.log` dupe target? The problem is `this.reversedArray = this.defaultArray;` because it doesn't create a copy of the array. – Andreas May 08 '19 at 05:27
  • 3
    @Andreas The array is logged and *then* reversed, but when the console is opened and the array is examined, it will be `54321` because `console.log` examines objects only on demand (it doesn't deep-save the state of the object as it was when it was logged). The linked console.log question describes why he's seeing `54321` (and why the reverse *seems* to be happening too fast) – CertainPerformance May 08 '19 at 05:29
  • Yes, I found the solution. Simple .slice() and it works... :D – Torben G May 08 '19 at 05:29
  • 1
    @TorbenG Note that `defaultArray` and `reversedArray` point to the same object. Both will contain the reversed array after your code has run. – user229044 May 08 '19 at 05:31

0 Answers0