0

I have just realized that I am unable to explain to myself why I can not do in JavaScript what I can do very easily in php. The issue is very simple and basic. Please compare the two following very short scripts and let me know what I miss to get.

<?php
$varA='aaa';
$AA='A';
echo 'var'.$AA; // outputs varA
echo ${'var'.$AA}; // outputs aaa
?>

Instead

<script type="text/javascript" >
var varA = 'aaa';
var AA = 'A';
alert('var'+AA); // outputs varA 
alert(---???---); // I wish to output aaa, I am unbale to get it! 
</script>
4
  • 4
    Err probably not, without using some nasty eval. If you need this sort of logic, you're probably doing it wrong. Commented Dec 11, 2011 at 13:21
  • 1
    In this case window['var'+AA] will work. But only because varA is a global variable. That said, there is probably a better to do what you want to do. Commented Dec 11, 2011 at 13:25
  • possible duplicate of Javascript Variable Variables Commented Dec 11, 2011 at 13:26
  • There's nothing wrong with eval or varvars per se. If you are using a scripting language and don't ever utilize the one feature that separates it from compiled languages, you are doing it wrong. But if newcomers just resort to them because they don't want to learn about array syntax, that's just as dingy. Commented Dec 11, 2011 at 13:29

3 Answers 3

3

This is called variable variables ands JS doesn't support them.
Note that you don't need them in PHP either. Use arrays instead, both in JS and PHP

Sign up to request clarification or add additional context in comments.

Comments

1

You can use eval to do something like that (not recommended, would re-test what you're doing), I'm not sure exactly what you need it for but thats how its done in JS.

var varA = 'aaa';
var AA = 'A';
alert('var'+AA); // outputs varA 
alert(eval('var' + AA)); // I wish to output aaa, I am unbale to get it! 

Shai

Comments

0

If your variables are within a scope that you know, then you can retrieve them like this:

// if in the global scope:
var varA = 'aaa';
var AA = 'A';
alert('var'+AA);
alert(window['var'+AA]);

However in most scopes you can't do this, unfortunately.

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.