【问题标题】:How to make string act like a variable name? [duplicate]如何使字符串像变量名一样起作用? [复制]
【发布时间】:2021-10-08 11:16:00
【问题描述】:

我见过很多其他类似的问题,但没有一个对我有帮助,因此我不觉得我的问题是重复的。关于这个案例的所有问题都试图为字符串变量附加一个新的“含义”,而我已经有了这些变量,只是想使用一个字符串来访问那些预先存在的变量。

我在 JS 中几乎没有带有 ID 的 div 和几个名称与这些 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;
}

【问题讨论】:

  • 如果id1id2id3在全局范围内,您可以从window获取它们。喜欢window[idName]

标签: javascript html string variables


【解决方案1】:

首先指定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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-21
    • 1970-01-01
    • 1970-01-01
    • 2012-07-18
    • 2017-02-05
    • 2016-10-09
    • 1970-01-01
    • 2011-04-24
    相关资源
    最近更新 更多