user5524348
user5524348

Reputation: 41

Get value of variable in javascript, which is combination of other two variable

I created variables in java script via loop as

var option1="some value 1";
var option2="some value 2";
var option3="some value 3";

Now If val=2 (val depends upon user input it may 1,2 or 3). I have to print option1, option2, option3 accordingly.

var finalopt="option"+val;
  alert(finalopt);

now output is (option2) I want output as (some value 2) because value of option 2 is some value 2.

Upvotes: 0

Views: 180

Answers (3)

kimbaudi
kimbaudi

Reputation: 15615

eval('option'+val);

It works, but other solutions are better.

Upvotes: 0

Suren Srapyan
Suren Srapyan

Reputation: 68675

Combine them in the object

var obj = {
   option1:"some value 1",
   option2:"some value 2",
   option3:"some value 3"
}

and use [] syntax for accessing properties

var finalopt="option"+val;
console.log(obj[finalopt]);

Code snippet

var obj = {
   option1:"some value 1",
   option2:"some value 2",
   option3:"some value 3"
}

var val = prompt('Input 1, 2 or 3');

var finalopt="option"+val;
console.log(obj[finalopt]);

Upvotes: 3

Milind Anantwar
Milind Anantwar

Reputation: 82251

You can use window object to get variable value by its name:

window[finalopt];

Upvotes: 2

Related Questions