可能重复:
Javascript 动态变量名
我将变量从 onClick 事件传递到 JavaScript 函数。总共有四个变量:两个告诉方向,两个告诉速度变化。我希望该函数评估选择了哪个方向(h_
或v_
,对于水平和垂直),然后应用必要的速度(更快或更慢)。
现在,我通过首先评估方向并changeSpeed
根据选择的方向调用不同的函数来成功地做到这一点。
我想做的是结合这些功能。在示例中,$(direction + "speed")
意味着成为h_speed
or v_speed
。
JavaScript 有能力做到这一点吗?(真诚的,米格尔)
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;
}
}
这是我的工作代码的两个版本:
版本 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;
}
}
版本 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;
}
}