Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I declare and use dynamic variables in JavaScript?

Tags:

javascript

Suppose I need to declare a JavaScript variable based on a counter, how do I do so?

var pageNumber = 1; var "text"+pageNumber; 

The above code does not work.

like image 970
user735566 Avatar asked May 10 '11 03:05

user735566


People also ask

How do you define a dynamic variable?

A dynamic variable is a variable you can declare for a StreamBase module that can thereafter be referenced by name in expressions in operators and adapters in that module. In the declaration, you can link each dynamic variable to an input or output stream in the containing module.

How do you declare a variable in JavaScript?

Always declare JavaScript variables with var , let , or const . The var keyword is used in all JavaScript code from 1995 to 2015. The let and const keywords were added to JavaScript in 2015. If you want your code to run in older browser, you must use var .

How do you dynamically name variables in a loop?

You can use eval() method to declare dynamic variables.

What is a dynamic variable example?

Dynamic Variable Overview The distinguishing characteristic of a dynamic variable is that its value can change while the application runs. For example, your application might maintain a threshold value that is compared to a field value in each tuple processed.


2 Answers

In JavaScript (as i know) there are 2 ways by which you can create dynamic variables:

  1. eval Function
  2. window object

eval:

var pageNumber = 1; eval("var text" + pageNumber + "=123;"); alert(text1); 

window object:

var pageNumber = 1; window["text" + pageNumber] = 123; alert(window["text" + pageNumber]); 
like image 158
bungdito Avatar answered Sep 28 '22 06:09

bungdito


How would you then access said variable since you don't know its name? :) You're probably better off setting a parameter on an object, e.g.:

var obj = {}; obj['text' + pageNumber] = 1; 

if you -really- want to do this:

eval('var text' + pageNumber + '=1'); 
like image 23
Nobody Avatar answered Sep 28 '22 06:09

Nobody