如何使字符串像变量名一样?



我见过很多类似的问题,但没有一个对我的情况有帮助,因此我不觉得我的问题是重复的。关于这个案例的所有问题都试图附加一个新的"意义"。到字符串变量,虽然我已经有了这些变量,只是想使用字符串能够达到那些预先存在的变量。

我有几个div与id和几个字典在JS与名称是相同的那些id。我想使用这些id,它们作为字符串返回,并将它们用作变量来访问这些字典。

我尝试使用window[item.id] = idName,但我相信我不理解它,因为它不起作用。

我代码:

<div id="id1" onclick="myfunc(this)"></div>
<div id="id2" onclick="myfunc(this)"></div>
<div id="id3" onclick="myfunc(this)"></div>
/* pre-existing variables I want to be able to use with IDs taken from function*/
id1={"name":"xxxx"}
id2={"name":"yyyy"}
id3={"name":"zzzz"}

function myfunc(item){
idName=item.id//returns string with id name
name=idName["name"]//doesn't work, as idName is a string and doesn't behave as a variable name;
}

先指定dictionary

则可以取id的对象…🙃

const dictionary = {
id1: {name: 'xxxx'},
id2: {name: 'yyyy'},
id3: {name: 'zzzz'},
};
const myfunc = (item)=>{
const idName = item.id;
const aName = dictionary[idName];
console.log(aName.name);
};
<div id="id1" onclick="myfunc(this)">one</div>
<div id="id2" onclick="myfunc(this)">one but 2</div>
<div id="id3" onclick="myfunc(this)">the third</div>

最新更新