Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find JavaScript variable by its name

Tags:

javascript

Is there a way to find JavaScript variable on the page (get it as an object) by its name? Variable name is available as a string constant.

like image 928
user59713 Avatar asked Apr 07 '09 09:04

user59713


People also ask

How do you find the value of a variable?

Use bracket notation to get an object's value by a variable key, e.g. obj[myVar] . The variable or expression in the brackets gets evaluated, so if a key with the computed name exists, you will get the corresponding value back.

How will you know the type of JavaScript variable?

Use the typeof operator to get the type of an object or variable in JavaScript. The typeof operator also returns the object type created with the "new" keyword.

What is JavaScript variable name?

var is the keyword that tells JavaScript you're declaring a variable. x is the name of that variable. = is the operator that tells JavaScript a value is coming up next. 100 is the value for the variable to store.

How do you call a variable value in JavaScript?

Example: var MyVariable = "Value of variable"; function readValue(name) { .... } alert(readValue("MyVariable"));


2 Answers

<script> var a ="test"; alert(a); alert(window["a"]); alert(eval("a")); </script> 
like image 92
Catalin DICU Avatar answered Sep 20 '22 06:09

Catalin DICU


All JS objects (which variables are) are available within their scope as named properties of their parent object. Where no explicit parent exists, it is implicitly the window object.

i.e.:

var x = 'abc'; alert(window['x']); //displays 'abc' 

and for a complex object:

var x = {y:'abc'}; alert(x['y']); //displays 'abc' 

and this can be chained:

var x = {y:'abc'}; alert(window['x']['y']); //displays 'abc' 
like image 22
annakata Avatar answered Sep 21 '22 06:09

annakata