2

I am using splice to add elements to an array at specified index.However In order to to do so I have to create a null array to add the elements at particular index.

If I use an empty array,the elements are not being pushed at specific instance.Right now i'm creating an empty array and then pushing null to that array.I want to know if I can achieve this with any other way.

This is what I'm doing:

arr:any[];
for(let i=0;i<userDefinedLength;i++)
{
    arr.push(null);
}
Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62
rock11
  • 718
  • 4
  • 17
  • 34

2 Answers2

2

You can use arr = new Array(userDefinedLength).fill(null);

Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62
0

Use fill:

arr: any[] = new Array(userDefinedLength).fill(null);

You can't use null[] unless you're just using the array as a placeholder:

arr: null[] = new Array(userDefinedLength).fill(null);
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79