简体   繁体   English

使用函数参数来访问JSON Array javascript

[英]Used function argument to access JSON Array javascript

I have a basic function taking an argument. 我有一个参与的基本功能。 I will use this argument to as index to access the array in JSON file. 我将使用此参数作为索引来访问JSON文件中的数组。 I want to take advantage of this argument instead of hard-coded inside the function. 我想利用这个参数而不是在函数内部进行硬编码。 However, for some reasons, javascript is not return me the right value. 但是,由于某些原因,javascript并没有给我正确的价值。

var obj = {
    "first":[
        ["aaaaa"],
        ["bbbbb"],
        ["ccccc"],
        ["ddddd"],
        ["eeeee"]                   
    ]
}

I have a javascript function to access the file. 我有一个javascript函数来访问该文件。

function addElement(ID) {
    console.log(obj.ID);
}

and now if I use 现在,如果我使用

addElement("first"); //this return me undefined. 

I do not want to explicitly mention obj.first in order to access the right JSON object. 我不想明确提到obj.first以访问正确的JSON对象。 I would like to make it more generic so that the method can be re-used. 我想使它更通用,以便可以重复使用该方法。 Am I missing anything here? 我在这里错过了什么吗?

Thanks... 谢谢...

JavaScript supports both dot notation and a property name literal ( obj.foo ), and brackets notation and a property name string ( obj["foo"] ).* In the latter case, the string can be the result of any expression. JavaScript支持点表示法和属性名称文字obj.foo ),括号表示法和属性名称字符串obj["foo"] )。*在后一种情况下,字符串可以是任何表达式的结果。

So you'd need brackets notation, not dot notation: 所以你需要括号表示法,而不是点符号:

function addElement(ID) {
    console.log(obj[ID]);
}

obj.ID accesses the property ID . obj.ID访问属性ID obj[ID] accesses the property whose name is the string from the variable ID . obj[ID]访问名称为变量ID的字符串的属性。


* Just for completeness: In ES6, it will support property name Symbol s in brackets notation as well, but that's not relevant to your code. *只是为了完整性:在ES6中,它也会用括号表示法支持属性名称Symbol ,但这与您的代码无关。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM