【问题标题】:Different results between if statement and Switch in Javascript [duplicate]Javascript中if语句和Switch之间的不同结果[重复]
【发布时间】:2020-08-03 10:12:04
【问题描述】:

我正在运行两个看似相同的语句来检查一个数字是正数、负数还是零。

if 语句返回预期结果。

switch 语句始终返回默认值。

为什么?

在这个例子中,我传递了“2”(type: number),然后在if 语句中得到+,在? 语句中得到?

// Verify whether a number is positive, negative or Zero:

function myFuncIf(y) {
  let result = null;
  console.log("y is " + y);
  console.log("y is " + typeof(y));

  if (y > 0) {
    return "+";
  } else if (y < 0) {
    return "-";
  } else {
    return "?";
  }
}

function myFuncSwitch(y) {
  let result = null;
  console.log("y is " + y);
  console.log("y is " + typeof(y));

  switch (y) {
    case (y > 0):
      result = "+";
      break;
    case (y < 0):
      result = "-";
      break;
    default:
      result = "?";
  }
  return result;
}
console.log(myFuncIf(2));
console.log(myFuncSwitch(2));

【问题讨论】:

标签: javascript


【解决方案1】:

switch 匹配 y 的值为2。 您的第一个 case 将匹配 True。 您的第二个将匹配 False

您可能希望您的开关看起来像这样:

  switch (Math.sign(y)) {
    case (1):
      result = "+";
      break;
    case (-1):
      result = "-";
      break;
    default:
      result = "?";
  }

在此处查看文档: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign

【讨论】:

  • 但是返回值是“?”虽然显然 2 大于 0..
  • 2 的值不等于True 也不等于False 所以它落入default 的情况。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-02
  • 1970-01-01
  • 2023-03-15
  • 2023-04-08
  • 2023-04-08
相关资源
最近更新 更多