问题描述
我已经找到了解决方案,但找不到任何有用的工作。
I’ve looked for solutions, but couldn’t find any that work.
我有一个名为 onlyVideo $ c的变量$ c>。
onlyVideo
字符串被传递到函数中。我想在函数内部设置变量 onlyVideo
。我该怎么做?
"onlyVideo"
the string gets passed into a function. I want to set the variable onlyVideo
inside the function as something. How can I do that?
(有很多变量可以调用到函数中,所以我需要它动态工作,而不是硬编码 if
语句。)
(There are a number of variables that could be called into the function, so I need it to work dynamically, not hard coded if
statements.)
编辑:可能有更好的方法来做你想做的事情。我在JavaScript冒险中很早就问过这个问题。查看JavaScript对象的工作原理。
一个简单的介绍:
// 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;
推荐答案
如果它是全局变量,那么 window [variableName]
或在你的情况下 window [onlyVideo]
应该可以解决问题。
If it's a global variable then window[variableName]
or in your case window["onlyVideo"]
should do the trick.
这篇关于在JavaScript中将字符串转换为变量名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!