Javascript-使用字符串作为对象引用
如果我有一堆对象,并且在这些对象中有与对象名称相同的字符串id,那么我如何使用该字符串来引用对象 例如:Javascript-使用字符串作为对象引用,javascript,javascript-objects,Javascript,Javascript Objects,如果我有一堆对象,并且在这些对象中有与对象名称相同的字符串id,那么我如何使用该字符串来引用对象 例如: //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 te
//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 ----- */
现在,如果我称之为:
myObj.id;
结果是test1是一个字符串。
如果我想用它从test1中获取数据,我该怎么做
"myObj.id".data
[myObj.id].data
^^^
这些不行
干杯,
Rich如果您的变量是在全局范围内定义的,则以下操作有效
window[ myObj.id ].data
如果你在一个函数的范围内,事情会变得更加困难。然后,最简单的方法是在window上的特定命名空间中定义对象,并检索类似于上述代码的对象。如果变量是在全局范围中定义的,则以下操作有效:
window[ myObj.id ].data
如果你在一个函数的范围内,事情会变得更加困难。然后,最简单的方法是在窗口上的特定名称空间中定义对象,并检索类似于上述代码的对象。将test1和test2存储在一个键值集合(也称为对象)中。然后像这样访问它:
collection[myObj.id].data
将test1和test2存储在键值集合(也称为对象)中。然后像这样访问它:
collection[myObj.id].data
如果要使用变量引用某个对象,请将其作为对象属性,而不是变量。如果它们有足够的相关性,可以通过这种方式访问,那么它们就有足够的相关性,可以有一个适当的数据结构来表达这种关系
var data = {
test1: {
id: "test1",
data: "Test 1 test 1 test 1"
},
test2: {
id: "test2",
data: "Test 2 test 2 test 2"
}
};
然后您可以访问:
alert( data[myObj.id] );
如果要使用变量引用某个对象,请将其作为对象属性,而不是变量。如果它们有足够的相关性,可以通过这种方式访问,那么它们就有足够的相关性,可以有一个适当的数据结构来表达这种关系
var data = {
test1: {
id: "test1",
data: "Test 1 test 1 test 1"
},
test2: {
id: "test2",
data: "Test 2 test 2 test 2"
}
};
然后您可以访问:
alert( data[myObj.id] );
所有答案都很好,谢谢你的帮助,如果将来有人发现这个,我将这样使用它:
var parent = {}
parent.test1 = {
id : "test1",
data : "Test 1 test 1 test 1"
}
parent.test2 = {
id : "test2",
data : "Test 2 test 2 test 2"
}
var myObj = null;
function setMyObj(obj){
myObj = obj;
}
setMyObj(parent.test1);
parent[myObj.id] = null;
//Test1 object is now null, not myObj!
所有答案都很好,谢谢你的帮助,如果将来有人发现这个,我将这样使用它:
var parent = {}
parent.test1 = {
id : "test1",
data : "Test 1 test 1 test 1"
}
parent.test2 = {
id : "test2",
data : "Test 2 test 2 test 2"
}
var myObj = null;
function setMyObj(obj){
myObj = obj;
}
setMyObj(parent.test1);
parent[myObj.id] = null;
//Test1 object is now null, not myObj!
myObj.data应该做这项工作。嘿,福坎-这是我的myObj数据-我想要test1的数据,它可能在这期间发生了变化!myObj.data应该做这项工作。嘿,福坎-这是我的myObj数据-我想要test1的数据,它可能在这期间发生了变化!Fwiw,这是我要用的解决方案,但我认为@sirko准确回答了它是如何提出的问题。Fwiw,这是我要用的解决方案,但我认为@sirko准确回答了它是如何提出的问题。