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

我有一个名为onlyVideo的变量。

"onlyVideo"字符串被传递给一个函数。我想在函数中设置变量onlyVideo。我该怎么做呢?

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

编辑:可能有更好的方法来做你正在尝试做的事情。我在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']方法仅在变量定义在全局作用域时有效。正确答案是“重构”。如果你能提供一个“Object”上下文,那么一个可能的通用解决方案就存在了,但是有一些变量是全局函数无法根据变量的作用域解析的。

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

其他回答

下面的代码可以方便地在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";

让我说得更清楚一点

function changeStringToVariable(variable, value){
window[variable]=value
}
changeStringToVariable("name", "john doe");
console.log(name);
//this outputs: john doe
let file="newFile";
changeStringToVariable(file, "text file");
console.log(newFile);
//this outputs: text file

如果它是一个全局变量,那么window[variableName] 或者在你的例子中,window["onlyVideo"]应该可以做到。

可以这样做

(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());

window['variableName']方法仅在变量定义在全局作用域时有效。正确答案是“重构”。如果你能提供一个“Object”上下文,那么一个可能的通用解决方案就存在了,但是有一些变量是全局函数无法根据变量的作用域解析的。

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