在没有其他可能性的情况下使用“else if”而不是“else”

Using "else if" instead of "else" when there is no other possibility

本文关键字:else if 其他 可能性 情况下      更新时间:2023-09-26

最近,我在Javascript中看到了一个这样的if/else块 - 尽管同样的问题可能适用于任何命令式语言

if (cond) {
  ....
} else if (!cond) {
  ....
}

问:elseif (!cond)的目的是什么? 如果没有其他可能性,我为什么不单独使用else呢?

我的观点是,if (!cond)是多余的,应该删除,我正在寻找指向文档的指针来证实这一点。

假设这两个条件相同(除了否定),这似乎只是(在我个人看来)写得不好的代码。

代码仍然很糟糕,但也许不是那么毫无意义:

var a = 1;
if(--a){
  el.innerHTML = 'here ' + a;
}else if(!(--a)){
  el.innerHTML += ', there ' + a;
}

显然没有一个el.innerHTML被执行。关键是,撇开可读性不谈,从逻辑上讲,结构根本不是多余的。

有一个边缘情况,这与 if 不同,即条件正在做某事。 但这不是理由,因为它会导致难以阅读的代码。

var silly = true;
function test() {
  silly = !silly;
  return silly;
}
if (test()) {
  console.log(silly);
} else if (!test()) {
  console.log(silly);
} else {
  console.log('silly')
}

以这种方式使用 else if; 它本质上是这样的:

if (cond)
{
    ....
}
else
{
    if (!cond)
    {
        ....
    }
}

所以是的,完全没有意义

我建议

  1. 最初有另一个选项被重构了
  2. 在不久的将来很可能有另一种选择(有些人不做YAGNI)
  3. 也许只是写得不好的代码。

正如你所说,如果语句中没有其他选项,那么就没有指向它

if (cond) {
  ....
} else if (!cond) {
  ....
}

意思与

if (cond) {
  ....
} else {
  ....
}

编写您看到的代码的人很可能在 if 中有更多的条件,并且在调试时简单地将其更改为 else if(!cond),而不是将其注释掉并添加else部分。