Skip to content
Advertisement

How to push new elements to an array with undefined index in JavaScript

I want to create array once and then just push values to it with any index , but i get Cannot read property 'push' of undefined error

I have following scenario

JavaScript

I want to use push randomly with any index

JavaScript

or

JavaScript

right now I want to define manually like neg[0] = []; , Is there any one way where i can just push to any index i want ?

Advertisement

Answer

Here’s a quick way to do exactly what you want.

JavaScript

Also it’s safer to check if an array already exists at this index, otherwise it will be replaced with an empty array – the above code will replace the array with an empty one if it already exists.

JavaScript

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement