Array of objects in TypeScript when you change a value the others are changed

0

I have this class in TypeScript

export class PageModel {

  constructor () {
  }

  Name: string;
  Content: string;
  Url: string;

}

And I created an array of this class

let test: PageModel[];
test = new Array(21);
test.fill(new PageModel());
test.fill(new PageModel());

I set this array with two instances:

test[0].Content = 'Firt instatance';
test[1].Content = 'Second instatance' ;
console.log (test[0].Content + test[1].Content);

However, in the console it is shown 'Second instance Second instance'

The second value writes the first value.

Is there any way to solve this problem?

    
asked by anonymous 28.05.2018 / 17:45

1 answer

1

See the documentation for Array.prototye.fill :

  

The method fill() fills all array values from the start index to a final index with a static value.

That is, all the positions of your array will be exactly the same instance and by modifying it in one of the indexes, the change will be reflected in all others. Since you have already started the array with 21 positions, you do not have to use fill() , just assign the instance at the desired index:

test[0] = new PageModel();
test[1] = new PageModel();

Or, if you do not want to initialize one by one, you can use fill to initialize them all with undefined and map them to a new instance of the class you want:

test = new Array(21).fill().map(it => new PageModel());

Example:

class PageModel {}

const test = new Array(5).fill().map(it => new PageModel())

test[0].name = 'foo'
test[1].name = 'bar'

console.log(test);
    
28.05.2018 / 18:19