this works in PHP:
$i = 4;
$fruit4 = 'apple';
$answer = $fruit{$i};
echo $answer; // apple
so i hoped this would work in javascript:
var i = 4;
var fruit4 = 'apple';
var answer = fruit{i};
print(answer);
but no luck! is there a way to do this using javascript?
NOTE: i realize this is more easily done with an array (var fruit[4] = 'apple') but that isn't an option this time due to pre-existing constraints.
thanks in advance!
Javascript has an function called eval, so try to use it. For example
var answer = eval("fruit"+ i);
eval('var answer = fruit' + i);
JavaScript has a way of accessing properties via square bracket notation so that you can use strings and variables to get to them.
For example, if your fruit4
(From the code in your post) is in the global scope in the browser:
var answer = window['fruit' + i];