SWITCH javascript 总是执行默认情况的问题 [英] trouble with SWITCH javascript always executing default case

查看:27
本文介绍了SWITCH javascript 总是执行默认情况的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗯,我有这个问题,我一直在处理,但我无法让它工作

well i have this trouble and ive been dealing with but i just cant get it to work

我有这个功能

function getDirections(dir)
{
var img;
switch(dir)
    {
    case 0:
    img+='N.png';
    break;  
    case 1:
    img+='NE.png';
    break;
    case 2:
    img+='E.png';
    break;
    case 3:
    img+='SE.png';
    break;
    case 4:
    img+='S.png';
    break;
    case 5:
    img+='SO.png';
    break;
    case 6: 
    img+='O.png';
    break;
    case 7:
    img+='NO.png';
    break;
    default:
    alert('enetered default but direction='+dir);
    }
return img;
}

很简单吧?现在我将此间隔设置为 5000 毫秒来调用 getDirections(variable),该函数在第一次调用时运行良好,但在此之后,它总是进入 default 子句,并且还提醒已输入默认值但方向 = dirvalue",我的意思是,即使 dir 是 0-7 之间的值,它也将始终进入默认值:但它会提醒该值,因此它应该进入其中一种情况.

quite simple right? now i have this interval set to 5000 ms to call getDirections(variable), the function works well the first time its called but after that , it always enter in the default clause and it also alerts the 'entered default but direction=dirvalue' , i mean even if dir is a value between 0-7 it will always enter to default: but it would alert the value so it was supossed to enter to one of the cases.

我用 else if 做了同样的事情,它起作用了,所以我不知道 SWITCH 有什么问题

i made the same using else if and it worked so i dont know what its wrong with SWITCH

if(dir==0){img+='N.png';}
else if(dir==1){img+='NE.png';}
else if(dir==2){img+='E.png';}
else if(dir==3){img+='SE.png';}
else if(dir==4){img+='S.png';}
else if(dir==5){img+='SO.png';}
else if(dir==6){img+='O.png';}
else if(dir==7){img+='NO.png';}

推荐答案

这很奇怪...尝试确保 dir 是 int,在切换之前执行此操作:

That is weird... try to make sure that dir is an int, do this before the switch:

dir = parseInt(dir);

如果警报正确显示值,它应该进入开关,但它仍然可以看起来"正确但具有不同的数据类型.手动进行转换以确保它是一个 int

If the alert shows the value correctly it should enter the switch, but still it can "look" correct but be of a different data type. Do the conversion manually to ensure it's an int

这篇关于SWITCH javascript 总是执行默认情况的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆