Refer to variable based on another variable
Ad
If I had the following code:
var number = 3;
var value1 = 22;
var value2 = 50;
var value3 = 63;
You can see that number = 3
and so from this I would like to get the value of value3
and say if number = 2;
I would like to get the value of value2
.
Is this possible? Thanks.
Ad
Answer
Ad
I would use an array instead, if possible.
var values = [22,50,63],
number = 2;
console.log(values[number]);
// 63
If this is not the case then the only other way I can think of is using eval
which has some risks associated with it.
Try:
var number = 3;
var value1 = 22;
var value2 = 50;
var value3 = 63;
eval('value' + number);
// 63
If they are global objects then they may already be available as a key on the window object:
window['value3']
// 63
Which means you can concat the string in the key name:
window['value' + num]
// 63
Ad
source: stackoverflow.com
Related Questions
Ad
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad