Javascript - 使用字符串连接设置变量

Chr*_*itz 7 javascript variables concatenation indirection

是否可以通过将两个字符串连接在一起形成名称来设置变量?

如果可能的话,我想根据用户点击的对象的类名确定要设置的变量.我知道我可以硬编码一堆if/else if语句,但如果我可以间接引用变量,那将会非常酷.我在想这样的事情:

var owner_read;
var group_read;

function setVariableIndirectly(object){
    var second = object.className; // returns "read"
    var first = object.parentElement.className; // returns "group"

    first + "_" + second = "set this as the new variable";
}
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点?

编辑:

这是数据来自的html.

<p class="owner">
    <span class="read" onclick="permissionClick(this)">r</span>
    <span class="write" onclick="permissionClick(this)">w</span>
    <span class="execute" onclick="permissionClick(this)">x</span>
</p>
Run Code Online (Sandbox Code Playgroud)

Bri*_*ock 10

这是可能的,但您必须警惕上下文和范围.

1.在浏览器环境中设置具有全局范围的变量:

window[str1 + str2] = value
Run Code Online (Sandbox Code Playgroud)

2.在节点环境中设置具有全局范围的变量:

global[str1 + str2] = value
Run Code Online (Sandbox Code Playgroud)

3.在一个闭包内并在该闭包内限定范围:

this[str1 + str2] = value
Run Code Online (Sandbox Code Playgroud)

在闭包内,全局和窗口仍将设置全局.请注意,如果您位于正在调用的函数中,则"this"可以引用另一个对象.


jfr*_*d00 6

目前尚不清楚您要完成的是什么,但您可以按名称访问变量作为对象的属性.

// this is the container to hold your named variables 
//    (which will be properties of this object)
var container = {};

function setVariableIndirectly(obj){
    var second = obj.className; // returns "read"
    var first = obj.parentNode.className; // returns "group"

    // this is how you access a property of an object 
    //    using a string as the property name    
    container[first + "_" + second] = "set this as the new variable";

   // in your example container["read_group"] would now be set
}
Run Code Online (Sandbox Code Playgroud)

如上所示,将变量放在您自己的容器对象上可能更好,但您也可以通过window对象的属性访问全局变量.