admin管理员组

文章数量:1180477

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

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");
Share Improve this question edited Feb 18, 2014 at 16:50 Sachin Jain 21.8k34 gold badges110 silver badges176 bronze badges asked Feb 18, 2014 at 16:07 Nadav MillerNadav Miller 4912 gold badges5 silver badges15 bronze badges 1
  • 1 MyArray = MyArray || []; – Cory Danielson Commented Feb 18, 2014 at 16:15
Add a comment  | 

5 Answers 5

Reset to default 19

Try this:

var MyArray = [];
MyArray[StringVariableName] = MyArray[StringVariableName] || [];
MyArray[StringVariableName][StringVariableName2] = MyArray[StringVariableName][StringVariableName2] || [];
MyArray[StringVariableName][StringVariableName2].push("whatever");

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

(MyArray[StringVariableName][StringVariableName2] || (MyArray[StringVariableName][StringVariableName2] = [])).push("whatever");

You could use the literal syntax to set things up like you'd have them:

var myObj = {
    StringVariableName: {
        StringVariableName2: []
    }
};

myObj.StringVariableName.StringVariableName2.push("whatever");

I think instead of using array in the first place, use object if your keys are not integers. In Javascript Arrays are also object So it is not wrong to do this

var a = [];
a['key'] = 'something';

console.log(a); //Gives []

I think it is conceptually wrong So instead of using Array to hold such pair of data you should use objects. See this:

var myObject = myObject || {};
myObject[str1] = myObject[str1] || {};
myObject[str1][str2] = myObject[str][str2] || [];

// Now myObject[str1][str2] is an array. Do your original operation

myObject[str1][str2].push("whatever");

To check without getting an error:

this snippet allows you to check if a chained object exists.

var x;
try{x=MyArray[name1][name2][name3][name4]}catch(e){}
!x||(x.push('whatever'));

from

https://stackoverflow.com/a/21353032/2450730

Shorthand creation of object chains in Javascript

this function allows you to create chained objects with a simple string.

function def(a,b,c,d){
 c=b.split('.');
 d=c.shift();//add *1 for arrays
 a[d]||(a[d]={});//[] for arrays
 !(c.length>0)||def(a[d],c.join('.'));
}

usage

var MyArray={};//[]
def(MyArray,'name1.name2.name3.name4');//name1+'.'+name2....

from

https://stackoverflow.com/a/21384869/2450730

both work also for arrays with a simple change.replace {} with []

if you have any questions just ask.

本文标签: Push to a javascript array if it existsif not then create it firstStack Overflow