Reputation: 41
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
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
Reputation: 82251
You can use window
object to get variable value by its name:
window[finalopt];
Upvotes: 2