避免 if 多层嵌套

1.把最有可能发生的条件写在前面,把最不可能出现的条件放到最后:

if(a > 0){
    // code
}else{
    // code
}

2.尽量少使用else:

可以使用 if + return ,先判断错误条件,然后立马结束函数,防止进入 else 分支。

if(ok){
    doSomething();
}else{
    console.log("error!");
    return;
}

修改为

if(!ok){
     console.log("error!");
    return;
}
doSomething();

3.多重 if 嵌套判断:

let ok = doSomething();
if(ok)
{
    ok = doSomething2();
    if(ok)
    {
        ok = doSomething3();
        if(!ok)
        {
            console.log("error!");
            return;
        }
    }
}

修改为

let ok = doSomething();
if(!ok)
{
    console.log("error!");
    return;
}

ok = doSomething2();
if(!ok)
{
    console.log("error2!");
    return;
}

ok = doSomething3();
if(!ok)
{
    console.log("error3!");
    return;
}

4.最后有非条件执行代码的情况:

A = doSomethingA();
if(A)
{
    B = doSomethingB();
    if(B)
    {
        C = doSomethingC();
        if(C)
        {
            console.log("error!");
            return;
        }
    }
}
doSomethingD();

修改为:

if(doSomethingA() && doSomethingB() && doSomethingC())
{
    doSomethingD();
}

5.利用条件差传递:

condition = true;

if(condition) condition = funA();

if(condition) condition = funB();

if(condition) condition = funC();

funD();

6.多条件判断,可写成 hash 表:

if(key == "apple")
{
    val = 1;
}else if(key == "orange")
{
    val = 2;
}else if(key == "banana")
{
    val = 3;
}

修改为

let obj = {"apple":1,"orange":2,"banana":3};
let val = obj[key];

7. switch / case

switch和if else在性能上是没有什么区别的,主要还是根据需求进行分析和选择。

  • 如果条件较小的话选用if else比较合适。

  • 相反,条件数量较大的话,就建议选用switch。

一般来说,if else适用于两个离散的值或者不同的值域。如果判断多个离散值,使用switch更加合适。

在大多数的情况下switch比if else运行的更加快。

在大多数情况下,switch的性能不会比if else低。switch的确在实质上跟if else if 完全一样的效果,不过在很多情况下,使用switch要比if else方便不少

比如经典的值等分支,匹配一些状态常量的时候,比if else结构方便许多,不用反复写xx == yy;
注意:千万不要忘记在每一个case语句后面放一个break语句。也可以放一个return或者throw。

case语句匹配expression是用 === 而不是 ==

END...

原文地址:https://www.cnblogs.com/sener/p/15668186.html