Else vs Else If

Else vs Else If

本文关键字:Else If vs      更新时间:2023-09-26

假设下面的脚本有问题:

function range(start, end, step){
  var theRange = [];
  var i = start;
  if(step === undefined){
    if(start < end)
      step = 1;
    else if(start > end)
      step = -1;
  }
  if(step < 0){
     for(;i >= end;i += step){
       theRange.push(i);
     }
  }else{ // just say Else?
    for(;i <= end;i += step){
      theRange.push(i);
    }
  }
  return theRange;
}
function sum(theRange){
  var theSum = 0;
  for(var i = 0; i < theRange.length; i++){
    theSum += theRange[i];
  }
  return theSum;
}
console.log(range(5,2));

我们试图弄清楚step是否小于0的部分-当step不小于0时使用Else是否更好,或者更好地使用Else if(step> 0)显式声明其他选项?

所以,基本上我想问的是,这段代码在任何方面(编译/执行时间,可读性,安全性等)会更好吗?:
function range(start, end, step){
  var theRange = [];
  var i = start;
  if(step === undefined){
    if(start < end)
      step = 1;
    else if(start > end)
      step = -1;
  }
  if(step < 0){
     for(;i >= end;i += step){
       theRange.push(i);
     }
  }else if(step > 0){ // explicitly state the other possible condition
    for(;i <= end;i += step){
      theRange.push(i);
    }
  }
  return theRange;
}
function sum(theRange){
  var theSum = 0;
  for(var i = 0; i < theRange.length; i++){
    theSum += theRange[i];
  }
  return theSum;
}
console.log(range(5,2));

逻辑上是有区别的。if (foo < 0) .. else ..匹配所有可能的情况。if (foo < 0) .. else if (foo > 0) .. 不匹配foo恰好为0的情况

除此之外,没有"安全"的好处或任何东西。这仅仅是基本的逻辑,您需要实现您的用例所需的逻辑。