Javascript-使用字符串作为对象引用 [英] Javascript - use string as object reference
问题描述
如果我有一堆对象,并且在这些对象中包含字符串"id"(与对象名称相同),该如何使用该字符串来引用该对象?
If I have a bunch of objects, and within these objects is the string "id" (which is the same as the object name) how can I use this string to reference the object?
示例:
//These objects are tests - note the id's are the same as the object name
var test1 = {
id : "test1",
data : "Test 1 test 1 test 1"
}
var test2 = {
id : "test2",
data : "Test 2 test 2 test 2"
}
/* ----- My Function ----- */
var myObj = null;
function setMyObj(obj){
myObj = obj;
}
setMyObj(test1);
/* ----- My Function ----- */
现在,如果我拨打以下电话:
Now, if I call the following:
myObj.id;
结果为"test1"(字符串). 如果要使用它从test1中获取数据,该怎么办?
The Result is "test1" (a string). If I want to use this to get the data from test1, how would I do so?
"myObj.id".data
[myObj.id].data
^^^
这些不起作用!
干杯, 丰富
推荐答案
如果您的变量是在全局范围内定义的,则可以使用以下方法
If your variables are defined on a global scope, the following works
window[ myObj.id ].data
如果您处于函数范围内,则事情会变得困难得多.然后,最简单的方法是在窗口上的特定命名空间中定义对象,然后检索与上述代码类似的对象.
If you are in a function's scope, things get a lot harder. Easiest way then is to define your objects in a specific namespace on window and retrieve the objects similar to the above code.
这篇关于Javascript-使用字符串作为对象引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!