<script> //in one script var someVarName_10 = 20; </script>
I want to get access to this variable from another script by name of variable. With window object its simple, is it possible with local variable?
I mean access this var by code like this:
<script> alert(all_vars['someVar' + 'Name' + num]); </script>
In JavaScript, dynamic variable names can be achieved by using 2 methods/ways given below. eval(): The eval() function evaluates JavaScript code represented as a string in the parameter. A string is passed as a parameter to eval(). If the string represents an expression, eval() evaluates the expression.
There are no dynamic variables in Java. Java variables have to be declared in the source code1. Depending on what you are trying to achieve, you should use an array, a List or a Map ; e.g. It is possible to use reflection to dynamically refer to variables that have been declared in the source code.
You write the string as normal but for the variable you want to include in the string, you write the variable like this: ${variableName} . For the example above, the output will be the same as the example before it that uses concatenation. The difference is, the interpolation example is much easier to read.
Declaring Variable: A variable can be either declared as a global or local variable. Variables can be declared by var, let, and const keywords. Before ES6 there is only a var keyword available to declare a JavaScript variable. Global Variables are the variables that can be accessed from anywhere in the program.
Do you want to do something like this?
<script> //in one script var someVarName_10 = 20; alert(window["someVarName_10"]); //alert 20 </script>
Update: because OP edited the question.
<script> num=10; alert(window['someVar' + 'Name_' + num]); //alert 20 </script>
I've noticed that everyone is advising global var creation this will lead to variables leak to global namespace. When you dynamically creating classnames or just variables it's easy to keep em local:
this['className'] = 123;
or
this['varName'] = 123;
Name-spacing would look like this:
vars = {}; vars['varName'] = 123; vars.varName // 123
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With