R
R
rinatoptimus2018-02-19 14:53:45
JavaScript
rinatoptimus, 2018-02-19 14:53:45

Why is the array overwritten?

There is a cycle

arr = [];
......
......
this.httpService.getList().subscribe(data => 
      {
        this.arr = data;
        for(let i=0; i<this.arr.length; i++) {
          this.arr.push(this.arr[i]);
          // this.arr = [];
        }
      }
    );

The question is in the title.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2018-02-19
@rinatoptimus

And what did you want to do?
Your loop will never end since you are constantly adding elements to the array. Before each iteration there is a check: And you have both i and this.arr.length after each iteration increase by 1 and as a result this.arr.length is always greater. Perhaps you wanted to do something like this:

this.httpService.getList().subscribe(data => {
  this.arr = [...this.arr, ...data];
});

or:
this.httpService.getList().subscribe(data => {
  this.arr = this.arr.concat(data);
});

If it is important to expand the old array, and not return a new one, then:
this.httpService.getList().subscribe(data => {
  data.forEach(el => this.arr.push(el));
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question