I need some help with a javascript principle.
I have a variable where part of the variable name is “dynamic”. Let me try to explain;
var name_city = "London";
var name_code = "500";
From the webpage I got an value named “type”. This will be “city” or “code”.
(I just make it manualy here for the sake of this example)
var type = "city";
So with “city” as the value of type, I now want to alert “name_city”.
But I have no idea on how to do this with javascript.
Does anyone know?
In php I think it will be like this:
$type = "city";
$varname = 'name_'. $type;
echo ${$varname};
I appreciate any help or some clue in the right direction 🙂
In order to accomplish this, you would need to store the data within an object literal, where you can access its keys dynamically. If you write those variables in the
global/windowobject you can access them the same way.This won’t work if you aren’t in the global scope (which actually, should not be the case at all). So you should store the data in a self-defined object
and then do the same thing, just access via