简体   繁体   English

如何使用if语句正确(javascript)

[英]How to use if statement right (javascript)

I got this code that works perfectly fine, just like i want it to, but then i want to extend it with else if, but the way i have done my code, that's not possible. 我得到的代码可以很好地工作,就像我想要的那样,但是如果我想用其他方式扩展它,那是不可能的。 Feel free to link some good site to learn from. 随意链接一些好的站点以进行学习。

if(wallLeft < marioLeft && wallLeftWidth > marioLeft)
{    

}
else
{
    newLeft = marioLeft - 5;
    mario.style.left = newLeft + "px";
}

//else if(wallLeftWidth < marioLeft && wallLeftWidth > marioLeftWidth)
{   }
else
{ //some code }

Inverse your conditions, writing if(...){}else{...} looks horrible and is really bad practice. 逆转您的条件,写if(...){}else{...}看起来很可怕,这实际上是一种不好的做法。 Additionally the order is if , else if , else , you cant use else if after else . 此外,该命令是ifelse ifelse ,你不能使用else if以后else

if( wallLeft > marioLeft || wallLeftWidth < marioLeft ) {
    newLeft = marioLeft - 5;
    mario.style.left = newLeft + "px";
} else if( wallLeftWidth > marioLeft || wallLeftWidth < marioLeftWidth) {
    //some code 
}

Your code is wrong. 您的代码是错误的。 Try this; 尝试这个;

if (wallLeft < marioLeft && wallLeftWidth > marioLeft) {
    newLeft = marioLeft - 5;
    mario.style.left = newLeft + "px";
} else if (wallLeftWidth < marioLeft && wallLeftWidth > marioLeftWidth) { 
    //some code 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM