Possible Duplicate:
Javascript dynamic variable name
I have variables being passed from an onClick event to a JavaScript function. There are four variables in total: two that tell the direction and two that tell the speed change. I want the function to evaluate which direction was chosen (either h_
or v_
, for horizontal and vertical) and then apply the necessary speed (either faster or slower).
Right now, I do this successfully by first evaluating the direction and calling a different changeSpeed
function depending on the direction which was chosen.
What I would like to do is combine these functions. In the example, $(direction + "speed")
is meant to become either h_speed
or v_speed
.
Is JavaScript equipped to do this? (sincerely, miguel)
var h_speed = 10;
var v_speed = 10;
function changeSpeed(speed, direction){
var direction = direction;
switch (speed)
{
case 'slower':
$($direction + "speed") = $($direction + "speed")*2;
break;
case 'faster':
$($direction + "speed") = $($direction + "speed")/2;
break;
}
}
Here are two versions of my working code:
VERSION 1
var h_speed = 10;
var v_speed = 10;
function identifyDirection(speed, direction){
switch (direction)
{
case 'vertical':
v_changeSpeed(speed);
break;
case 'horizontal':
h_changeSpeed(speed);
break;
}
}
function h_changeSpeed(speed){
switch (speed)
{
case 'slower':
h_speed = h_speed*2;
break;
case 'faster':
h_speed = h_speed/2;
break;
}
}
function v_changeSpeed(speed){
switch (speed)
{
case 'slower':
v_speed = v_speed*2;
break;
case 'faster':
v_speed = v_speed/2;
break;
}
}
VERSION 2
/**
* the changeSpeed functions' arguments
* are placed directly in the function that
* determines whether horizontal or vertical
* speed is changing.
*
*/
function changeSpeed(speed, direction){
switch (direction)
{
case 'vertical':
switch (speed)
{
case 'slower':
v_speed = v_speed*2;
break;
case 'faster':
v_speed = v_speed/2;
break;
}
break;
case 'horizontal':
switch (speed)
{
case 'slower':
h_speed = h_speed*2;
break;
case 'faster':
h_speed = h_speed/2;
break;
}
break;
}
}