2

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

var neg = [];

I want to use push randomly with any index

neg[0].push([1,2]);

or

neg[22].push([1,2]);

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 ?

ludovico
  • 2,103
  • 1
  • 13
  • 32
Gracie williams
  • 1,287
  • 2
  • 16
  • 39

5 Answers5

3

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

var arr = [];

(arr[0]=[]).push([1,2]);

console.log(arr)

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.

// creates an array at index 0 only if there's no array at this index.
// pushes an array of [1, 2] to the existing array at 0 index
// or the newly created empty one.
(arr[0] || (arr[0] = [])).push([1, 2]);;

var arr = [];

arr[0] = [1];

(arr[0]||(arr[0]=[])).push(2,3);

console.log(arr)
Khalid Ali
  • 1,224
  • 1
  • 8
  • 12
1

You are going to have to set it to an empty array before you can push it.

neg[0] = neg[0] || []
neg[0].push([1,2]);
epascarello
  • 204,599
  • 20
  • 195
  • 236
1

Push will add elements to the end of an array. For example:

var neg = [];
neg.push(3); //this will add the number 3 to the end of your array

The problem here is your trying to add a value to an undefined element:

var neg = [];
neg[0].push([1,2]); // <-- neg[0] is not defined at this moment, and you're treating it as an array object.

If you define your elements as an array, you will not get such an error:

var neg = [];
neg[0] = [];
neg[22] = [];

neg[0].push([1,2]);
neg[22].push([1,2]);

Alternatively (and this is probably what you're probably looking for), you can set the value for any element of your array with the desired index:

var neg = [];

neg[0] = [1,2];
neg[22] = [1,2];
ludovico
  • 2,103
  • 1
  • 13
  • 32
0

You can specify how large the array will be if you know ahead of time, for example var neg = new Array(40); will create a new array with 40 undefined elements.

Once that is created, you can change the value at any index as long as 0 <= index <= 39.

Dana Woodman
  • 4,148
  • 1
  • 38
  • 35
Jud
  • 1,324
  • 3
  • 24
  • 47
  • 1
    well, unlike in other languages, in JavaScript you can define an array of an undefined length (```var myArray=[]```). Also, note that push will add elements to the end of the array (even beyond it's initial length) and returns the new length of the array --example here: https://jsbin.com/nuriqiqixa/edit?html,js,console,output – ludovico Apr 22 '19 at 19:25
  • `var neg = [40]` creates an array with one item with the value `40` not an array with `40` items. – Dana Woodman Jul 13 '22 at 23:31
-1

You can use array.splice(your_index, 0, your_element); to push an element into an array at the given index.