简体   繁体   English

我可以在 JavaScript 中使用变量作为变量名吗?

[英]Can I use a variable as variable name in JavaScript?

I am trying to use a variable as another variables name.我正在尝试使用一个变量作为另一个变量名称。 For example, I have the following:例如,我有以下内容:

var dynamicname = 'name1_'

And I am trying to set it as the name of a new variable like this:我试图将其设置为这样的新变量的名称:

dynamicname + '2' = 'myvalue'

This obviously isn't working but is there a way to achieve this?这显然不起作用,但有没有办法实现这一目标? Would eval be suitable? eval合适吗?

Slightly off, but a possible answer to this using objects can be something along the lines of: 略有偏离,但是使用对象对此的可能答案可能是:

const obj = {
    [ dynamicNameVar + '2' ]: ...
}

Or, for the old-school folks, 或者,对于那些守旧派的人,

var obj = {};
obj[dynamicNameVar + '2'] = ...

I hope this helps! 我希望这有帮助! :) :)

As mentioned in the comments, you should never do this. 如评论中所述,您永远都不要这样做。

But if you want to do this: 但是,如果您想这样做:

var name ="name1_";

// declare a new var as name1_test and set it to 'TestWorked'.
eval("var "+name+"test = 'TestWorked'");

// prints value of name1_test ('TestWorked')
console.log(name1_test);

For just keeping an indicator/flag for a seen video, you could use Set or if you need more stored information, take a Map instead of using dynamically created variables where you still need to create an accessor for the variable as well. 如果只为观看的视频保留指示器/标记,则可以使用Set如果需要更多存储的信息,则可以使用Map而不是使用动态创建的变量,在该情况下,您仍然需要为变量创建访问器。

 var seen = new Set; console.log(seen.has('foo')); // false; seen.add('foo'); console.log(seen.has('foo')); // true; 

To my knowledge, this is the best method.据我所知,这是最好的方法。

 window["varname"]=32; console.log(varname)

As others said, this is a bad practice and you should use objects. 正如其他人所说,这是一种不好的做法,您应该使用对象。 But if anyone really needs to do this for some reason, the right way to do is to use the window object, instead of eval. 但是,如果由于某些原因确实需要执行此操作,则正确的方法是使用window对象而不是eval。 In your case it would be: 您的情况是:

var dynamicname = 'name1_'
window[dynamicname + '2'] = 'myvalue'

You can do alert(name1_2) and it would show "myvalue". 您可以执行alert(name1_2) ,它将显示“ myvalue”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM