0

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.

HDJEMAI
  • 9,436
  • 46
  • 67
  • 93
  • https://stackoverflow.com/questions/4852017/how-to-initialize-an-arrays-length-in-javascript – developer033 Dec 23 '17 at 00:41
  • That does not address the question here. The question is why it creates a single member in the array with a value of i, rather than amount i of members with null values. The link you gave is literally the opposite, it does not address TypeScript but rather JavaScript. P.S: If I do use new Array(4) it'd make an array with 4 members, but new Array(i) when i = 4 yields an array with a single member with a value of 4. – Mohammad Osama Dec 23 '17 at 02:13
  • If you break on the counter method is **i** definitely a number? – JayChase Dec 23 '17 at 04:10
  • It is clearly stated that it is a number in the function declaration. I'd believe that even if I do call it with anything but a number, it would automatically switch it. – Mohammad Osama Dec 27 '17 at 20:40

1 Answers1

1

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

HDJEMAI
  • 9,436
  • 46
  • 67
  • 93