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

余生长醉 提交于 2020-01-02 02:22:09

问题


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

回答1:


Try this:

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



回答2:


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

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

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



回答3:


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



回答4:


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.




回答5:


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

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


来源:https://stackoverflow.com/questions/21859132/push-to-a-javascript-array-if-it-exists-if-not-then-create-it-first

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!