如何仅使用 2 个 if 语句检查 3 种可能性

ash*_*nka 0 javascript

创建一个接收整数作为参数并返回字符串的函数,例如:

  • 如果数字是 4 的倍数,则返回“Foo”
  • 如果数字是 7 的倍数,则返回“Bar”
  • 如果数字是 4 和 7 的倍数,则返回“FooBar”

这可以使用 3 个 if 语句来完成,如下所示,但是可以只使用 2 个 if 语句来完成吗?

const intToStr = (intVal) => {

    if (intVal % 4 == 0 && intVal % 7 == 0) {
        return "FooBar";
    }
    
    if (intVal % 7 == 0) {
        return "Bar";
    } 
    
    if (intVal % 4 == 0) {
        return "Foo";
    }

}

console.log(intToStr(4*7));
console.log(intToStr(7));
console.log(intToStr(4));
Run Code Online (Sandbox Code Playgroud)

Roc*_*ims 6

是的,只需 2 个 if 语句即可完成。

const intToStr = (intVal) => {
  let str = '';

  if (intVal % 4 === 0) {
    str += "Foo";
  }

  if (intVal % 7 === 0) {
    str += "Bar";
  }
  
  return str;
}

console.log(intToStr(4*7));
console.log(intToStr(7));
console.log(intToStr(4));
Run Code Online (Sandbox Code Playgroud)