Javascript - set a variable using concatenation of strings [duplicate]

心已入冬 提交于 2019-12-01 05:47:51

It's not clear exactly what you're trying to accomplish, but you can access variables by name as properties of an object.

// 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
}

It's probably better to put your variables on your own container object as shown above, but you can also access global variables via properties on the window object.

This is possible but you have to be wary of context and scope.

1. To set variable with global scope in browser environment:

window[str1 + str2] = value

2. To set variable with global scope in node environment:

global[str1 + str2] = value

3. Within a closure and scoped within that closure:

this[str1 + str2] = value

Within the closure, global and window will still set the global. Note that if you are within a function that is being called, 'this' could refer to another object.

You can set a global variable this way:

window[first + "_" + second] = "set this as the new variable";

and access it as:

console.log(group_read);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!