Mohammad Osama
Mohammad Osama

Reputation: 59

Dynamic arrays in TypeScript (Angular2+)

I'm trying to create a dynamic array based on an integer, so, assuming integer i = 3, it would create an array with length 3.

counter (i: number) {
  return new Array(i);
}

Why does this return an array with length 1 and a member with a value of i rather than an array with length i?

EDIT: A walkaround to what I'm trying to do is:

counter (i: number) {
  var a = new Array();
  for (var x = 0; x < i; x++)
    a.push(x);

  return a;
}

I'm just curious about the behavior of the array constructor.

Upvotes: 0

Views: 6540

Answers (1)

HDJEMAI
HDJEMAI

Reputation: 9800

By testing your example with angular core 5.0.0, the function will create an array with length 4 for example, and when you do the resulting variable.length it will equal to 4. so, the given link before has all what you need to understand the result.

here is a demo that demonstrate that:

https://stackblitz.com/edit/angular-9effym?file=app%2Fapp.component.html

(direct link, for debugging with dev tools: https://angular-9effym.stackblitz.io)

result

Hello !

Array length: 4

value 0 = undefined
value 1 = undefined
value 2 = undefined
value 3 = undefined

code:

app.component.html:

<hello name="{{ name }}"></hello>
<div>
  <br>
  Array length: {{xx.length}}
  <br>
  <br>
  <div *ngFor="let value of xx; let i = index">
      value {{i}} = {{value+''}}
  </div>
</form>
<br>

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {

  xx:any;


  ngOnInit() {

      this.xx = this.counter(4);

  }

  counter(i: number){
    return new Array(i);
  }
}

Note:

since we didn't initialize the elements of the array, there content will be undefined, I demonstrated that by converting the content to string using {{value+''}} in the template

Upvotes: 1

Related Questions