在 JavaScript 中将字符串转换为变量名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5613834/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:03:47  来源:igfitidea点击:

Convert string to variable name in JavaScript

javascriptvariables

提问by switz

I've looked for solutions, but couldn't find any that work.

我一直在寻找解决方案,但找不到任何有效的解决方案。

I have a variable called onlyVideo.

我有一个名为onlyVideo.

"onlyVideo"the string gets passed into a function. I want to set the variable onlyVideoinside the function as something. How can I do that?

"onlyVideo"字符串被传递给一个函数。我想onlyVideo将函数内部的变量设置为某物。我怎样才能做到这一点?

(There are a number of variables that could be called into the function, so I need it to work dynamically, not hard coded ifstatements.)

(有许多变量可以被调用到函数中,所以我需要它动态工作,而不是硬编码if语句。)

Edit: There's probably a better way of doing what you're attempting to do. I asked this early on in my JavaScript adventure. Check out how JavaScript objects work.

编辑:可能有更好的方法来做您正在尝试做的事情。我很早就在我的 JavaScript 冒险中问过这个问题。查看 JavaScript 对象是如何工作的。

A simple intro:

简单介绍:

// create JavaScript object
var obj = { "key1": 1 };

// assign - set "key2" to 2
obj.key2 = 2;

// read values
obj.key1 === 1;
obj.key2 === 2;

// read values with a string, same result as above
// but works with special characters and spaces
// and of course variables
obj["key1"] === 1;
obj["key2"] === 2;

// read with a variable
var key1Str = "key1";
obj[key1Str] === 1;

回答by ingo

If it's a global variable then window[variableName]or in your case window["onlyVideo"]should do the trick.

如果它是一个全局变量,那么window[variableName]或者在您的情况下window["onlyVideo"]应该可以解决问题。

回答by goggin13

Javascript has an eval()function for such occasions:

Javascript 有这样一个eval()功能:

function (varString) {
  var myVar = eval(varString);
  // .....
}

Edit: Sorry, I think I skimmed the question too quickly. This will only get you the variable, to set it you need

编辑:对不起,我想我过快地浏览了这个问题。这只会为您提供变量,以设置您需要的变量

function SetTo5(varString) {
  var newValue = 5;
  eval(varString + " = " + newValue);
}

or if using a string:

或者如果使用字符串:

function SetToString(varString) {
  var newValue = "string";
  eval(varString + " = " + "'" + newValue + "'");
}

But I imagine there is a more appropriate way to accomplish what you're looking for? I don't think eval() is something you really want to use unless there's a great reason for it. eval()

但我想有更合适的方法来完成你正在寻找的东西吗?我不认为 eval() 是你真正想要使用的东西,除非有很好的理由。评估()

回答by jm0

As far as eval vs. global variable solutions...

至于 eval 与全局变量的解决方案......

I think there are advantages to each but this is really a false dichotomy. If you are paranoid of the global namespace just create a temporary namespace & use the same technique.

我认为每个人都有优点,但这确实是一种错误的二分法。如果您对全局命名空间感到偏执,只需创建一个临时命名空间并使用相同的技术。

var tempNamespace = {};
var myString = "myVarProperty";

tempNamespace[myString] = 5;

Pretty sure you could then access as tempNamespace.myVarProperty (now 5), avoiding using window for storage. (The string could also be put directly into the brackets)

很确定您可以作为 tempNamespace.myVarProperty(现在是 5)访问,避免使用 window 进行存储。(字符串也可以直接放在括号中)

回答by Shaz

var myString = "echoHello";

window[myString] = function() {
    alert("Hello!");
}

echoHello();

Say no to the evileval. Example here: https://jsfiddle.net/Shaz/WmA8t/

邪恶的评估说不。这里的例子:https: //jsfiddle.net/Shaz/WmA8t/

回答by Eric Conner

You can access the window object as an associative array and set it that way

您可以将窗口对象作为关联数组访问并以这种方式设置

window["onlyVideo"] = "TEST";
document.write(onlyVideo);

回答by Lance Caraccioli

The window['variableName'] method ONLY works if the variable is defined in the global scope. The correct answer is "Refactor". If you can provide an "Object" context then a possible general solution exists, but there are some variables which no global function could resolve based on the scope of the variable.

window['variableName'] 方法仅在变量定义在全局范围内时才有效。正确答案是“重构”。如果您可以提供“对象”上下文,则存在可能的通用解决方案,但有一些变量是全局函数无法根据变量范围解析的。

(function(){
    var findMe = 'no way';
})();

回答by Lance Caraccioli

If you're trying to access the property of an object, you have to start with the scope of windowand go through each property of the object until you get to the one you want. Assuming that a.b.chas been defined somewhere else in the script, you can use the following:

如果您尝试访问对象的属性,则必须从对象的作用域开始window并遍历对象的每个属性,直到找到您想要的属性。假设a.b.c已在脚本的其他地方定义,您可以使用以下内容:

var values = window;
var str = 'a.b.c'.values.split('.');

for(var i=0; i < str.length; i++)
    values = values[str[i]];

This will work for getting the property of any object, no matter how deep it is.

这将适用于获取任何对象的属性,无论它有多深。

回答by Eliyah Sundstr?m

You can do like this

你可以这样做

var name = "foo";
var value = "Hello foos";
eval("var "+name+" = '"+value+"';");
alert(foo);

回答by David Spector

The following code makes it easy to refer to each of your DIVs and other HTML elements in JavaScript. This code should be included just before the tag, so that all of the HTML elements have been seen. It should be followed by your JavaScript code.

以下代码使您可以轻松地在 JavaScript 中引用您的每个 DIV 和其他 HTML 元素。此代码应包含在标记之前,以便可以看到所有 HTML 元素。它应该跟在您的 JavaScript 代码之后。

// For each element with an id (example: 'MyDIV') in the body, create a variable
// for easy reference. An example is below.
var D=document;
var id={}; // All ID elements
var els=document.body.getElementsByTagName('*');
for (var i = 0; i < els.length; i++)
    {
    thisid = els[i].id;
    if (!thisid)
        continue;
    val=D.getElementById(thisid);
    id[thisid]=val;
    }

// Usage:
id.MyDIV.innerHTML="hello";

回答by yunzen

It can be done like this

可以这样做

(function(X, Y) {
  
  // X is the local name of the 'class'
  // Doo is default value if param X is empty
  var X = (typeof X == 'string') ? X: 'Doo';
  var Y = (typeof Y == 'string') ? Y: 'doo';
  
  // this refers to the local X defined above
  this[X] = function(doo) {
    // object variable
    this.doo = doo || 'doo it';
  }
  // prototypal inheritance for methods
  // defined by another
  this[X].prototype[Y] = function() {
    return this.doo || 'doo';
  };
  
  // make X global
  window[X] = this[X];
}('Dooa', 'dooa')); // give the names here

// test
doo = new Dooa('abc');
doo2 = new Dooa('def');
console.log(doo.dooa());
console.log(doo2.dooa());