使用Javascript - 使用字符串对象引用(Javascript - use string

2019-10-16 20:51发布

如果我有一堆的对象,这些对象中的字符串“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;

结果是“测试1”(一个字符串)。 如果我想用这个来从test1的数据,我会怎么做呢?

"myObj.id".data
[myObj.id].data

^^^

这些不工作!

干杯,丰富

Answer 1:

如果您的变量是在全球范围内定义,下列作品

window[ myObj.id ].data

如果你是在一个函数的范围,事情就会变得更难。 那么最简单的方法是在窗口中特定的命名空间来定义你的对象和检索类似上面的代码中的对象。



Answer 2:

(又名对象)店铺TEST1和TEST2键值集合然后访问它喜欢:

collection[myObj.id].data


Answer 3:

如果你想使用一个变量来指代什么,然后做出的东西一个对象的属性,而不是一个变量。 如果它们充分地与以这种方式来进行访问,那么他们有一个合适的数据结构来表示这种关系充分相关。

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] );


Answer 4:

伟大的答案所有,感谢您的帮助,如果任何一个在将来发现这一点,这是我要如何使用它:

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!


文章来源: Javascript - use string as object reference