问题描述
我一直在寻找解决方案,但找不到任何有效的方法.
I’ve looked for solutions, but couldn’t find any that work.
我有一个名为 onlyVideo
的变量.
I have a variable called onlyVideo
.
"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 中将字符串转换为变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!