Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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!

share|improve this question
    
Thankfully it's not possible to do in js (in a general case) –  zerkms 1 hour ago
    
thanks for weighing in, but why should we be grateful for that if it isn't helpful? –  JoshR 1 hour ago
    
Because it allows you to make terrible code even more terrible too easily. –  zerkms 1 hour ago
    
why is it terrible? when you're working with pre-defined numbered variables (with an unpredictable pattern) and can't use an array, what choice does one have? –  JoshR 1 hour ago
    
"and can't use an array" --- I don't make stupid constraints to myself at first place. If it's a collection - it's either an array or an object. Period. –  zerkms 1 hour ago

3 Answers 3

up vote 0 down vote accepted

Javascript has an function called eval, so try to use it. For example

var answer = eval("fruit"+ i);
share|improve this answer
    
perfect! thanks, hayk. i probably should have thought of this, having used the word "eval" in my question's title! thankfully @zerkms was mistaken and/or just trolling. –  JoshR 42 mins ago

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];
share|improve this answer
    
What if it's not in a global scope? What if it runs not in a browser? –  zerkms 1 hour ago
3  
If it's not global, use appropriate scope. I said "for example". I mean, honestly. :/ –  JAAulde 1 hour ago
    
This answer's a bit esoteric, but much better than using eval imo. –  David Titarenco 1 hour ago
eval('var answer = fruit' + i);
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.