Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get global variable dynamically by name string in JavaScript

Tags:

javascript

<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> 
like image 852
Igor Golodnitsky Avatar asked Dec 17 '09 10:12

Igor Golodnitsky


People also ask

How do you dynamically name a variable in JavaScript?

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.

How do you make a variable name dynamic in Java?

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.

How do you call a variable in a string in JavaScript?

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.

Can we declare global variable in JavaScript?

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.


2 Answers

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> 
like image 66
YOU Avatar answered Oct 04 '22 04:10

YOU


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 
like image 27
Andrew Shatnyy Avatar answered Oct 04 '22 03:10

Andrew Shatnyy