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);
}
3

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.