Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Push to a javascript array if it exists, if not then create it first

Is there a way for this line to always work and not throw TypeError: Cannot read property 'Whatever' of undefined

var MyArray = [];
MyArray[StringVariableName][StringVariableName2].push("whatever");
like image 909
Nadav Miller Avatar asked Feb 18 '14 16:02

Nadav Miller


People also ask

How do you push an object into an array at first position JavaScript?

Adding new elements at the beginning of the existing array can be done by using the Array unshift() method. This method is similar to push() method but it adds an element at the beginning of the array.

How do you push an element to the beginning of an array?

The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.

How do you push an element to an empty array?

How do you push values in an empty array? Answer: Use the array_push() Function You can simply use the array_push() function to add new elements or values to an empty PHP array.

Does push add to front or back of array?

The push() method is similar to the unshift() method as it adds an element to the end of an array rather than the beginning. It returns the length of the new array and, like the unshift() method, can be used to add more than one element.


1 Answers

You could even, through the power of expressions, do this with a one-liner.

(MyArray[StringVariableName][StringVariableName2] || (MyArray[StringVariableName][StringVariableName2] = [])).push("whatever");
like image 64
Jack Avatar answered Sep 20 '22 09:09

Jack