javascript 如果存在则推送到javascript数组,如果不存在则先创建它

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21859132/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 21:51:54  来源:igfitidea点击:

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

javascriptarraysobject

提问by Nadav Miller

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

有没有办法让这条线始终工作而不是抛出 TypeError: Cannot read property 'Whatever' of undefined

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

回答by ppoliani

Try this:

试试这个:

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

回答by sachinjain024

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

我认为首先不要使用数组,如果您的键不是整数,请使用对象。在 Javascript 中数组也是对象所以这样做并没有错

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

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

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

我认为它在概念上是错误的,所以不要使用 Array 来保存这样的数据对,而应该使用对象。看到这个:

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

回答by Laoujin

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

你可以使用文字语法来设置你想要的东西:

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

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

回答by cocco

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

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

Shorthand creation of object chains in Javascript

在 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

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

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

两者都适用于具有简单更改的数组。替换{}[]

if you have any questions just ask.

如果你有问题,就问吧。

回答by Hyman Tuck

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

您甚至可以通过表达式的强大功能,使用单线来做到这一点。

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