问题
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?
Example:
//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;
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
^^^
These don't work!
Cheers, Rich
回答1:
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.
回答2:
Store test1 and test2 in a key-value collection (aka an object.) Then access it like:
collection[myObj.id].data
回答3:
If you want to refer to something using a variable, then make that something an object property, not a variable. If they are sufficiently related to be accessed in that way, then they are sufficiently related to have a proper data structure to express that relationship.
var data = {
test1: {
id: "test1",
data: "Test 1 test 1 test 1"
},
test2: {
id: "test2",
data: "Test 2 test 2 test 2"
}
};
Then you can access:
alert( data[myObj.id] );
回答4:
Great answers all, thanks for the help, in case any one finds this in future, this is how I'm going to use it:
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!
来源:https://stackoverflow.com/questions/11102611/javascript-use-string-as-object-reference