Javascript - set a variable using string concatenation

Is it possible to set a variable by combining two lines together to form a name?

If at all possible, I would like to determine which variable to set based on the class names of the objects that the user clicks. I know that I can hard-code a bunch of if / else if, but it would be really cool if I indirectly touched variables indirectly. I thought something like this:

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"; } 

Is there any way to do this?

EDIT:

Here is the html from which the data is coming.

 <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> 
+6
source share
3 answers

It is not clear what exactly you are trying to execute, but you can refer to variables by name as object properties.

 // 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 is probably best to put your variables on your own container object, as shown above, but you can also access global variables through the properties of the window object.

+6
source

This is possible, but you must be careful with context and scope.

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

 window[str1 + str2] = value 

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

 global[str1 + str2] = value 

3. Within the closure and within this closure:

 this[str1 + str2] = value 

Inside the closure, the global and the window will still set global. Please note: if you are in a called function, 'this' may refer to another object.

+9
source

You can set a global variable as follows:

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

and access it as:

 console.log(group_read); 
+1
source

Source: https://habr.com/ru/post/957094/


All Articles