Javascript - 使用字符串作为对象引用

Javascript - use string as object reference

本文关键字:对象引用 字符串 Javascript      更新时间:2023-09-26

如果我有一堆对象,并且这些对象中有字符串"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 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

^^^

这些不起作用!

干杯富

如果您的变量是在全局范围内定义的,则以下工作

window[ 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 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!