0

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!

8
  • Thankfully it's not possible to do in js (in a general case) Commented Sep 4, 2014 at 23:05
  • thanks for weighing in, but why should we be grateful for that if it isn't helpful? Commented Sep 4, 2014 at 23:06
  • Because it allows you to make terrible code even more terrible too easily. Commented Sep 4, 2014 at 23:07
  • 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? Commented Sep 4, 2014 at 23:11
  • i think you misunderstood me. when i say "pre-existing constraints" i mean "not of my own making." i'm working with a client's dataset in which fields are named something like var1, var2, var3, etc. if it were up to me, i'd certainly use an array, and i wouldn't be here asking for help. why even answer if you can't contribute? no need to answer that. just think on it. Commented Sep 4, 2014 at 23:28

3 Answers 3

1

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];
Sign up to request clarification or add additional context in comments.

3 Comments

What if it's not in a global scope? What if it runs not in a browser?
If it's not global, use appropriate scope. I said "for example". I mean, honestly. :/
This answer's a bit esoteric, but much better than using eval imo.
0

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

var answer = eval("fruit"+ i);

1 Comment

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.
0
eval('var answer = fruit' + i);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.