为什么我们应该在 switch 条件下而不是在 if 条件下解析值?

杰克逊·杰加西森

function runif() {
  let a = document.getElementById('test').value;
  if (a == 1) {
    console.log("works");
  }
}

function runswitch() {
  let a = document.getElementById('test').value;
  switch (a) {
    case 1:
      console.log("working");
      break;

    default:
      break;
  }
}

function runswitchOne() {
  let a = parseInt(document.getElementById('test').value);
  switch (a) {
    case 1:
      console.log("working");
      break;

    default:
      break;
  }
}
<form action="">
  <input type="text" id="test">
  <input type="button" onclick="runif()" value="click to check if">
  <input type="button" onclick="runswitch()" value="click to check without parseInt">
  <input type="button" onclick="runswitchOne()" value="click to check with parseInt">
</form>

这是我用一个文本输入和两个按钮创建的表单。

其中 if 语句识别输入并执行操作

但是在 switch 我必须让它解析才能识别

我不明白为什么它有效?我知道文本输入会引起刺痛,但如果是这样,if() 语句如何在不解析的情况下工作?

通常我们使用 if(a == "1") 来比较字符串而不是 if(a==1)?

但即便如此它也能工作

马蒙

switch case进行严格比较(检查valuetype)。

元素是字符串类型。内部 switch case值是int类型并且不匹配。因此,如果不进行转换,您的代码将无法工作。

但是当使用时a == 1检查而不检查类型"1" == 1评估为true如果您进行严格比较(例如,===),则"1" === 1计算结果为false,因为在这种情况下,虽然相等但类型不相等。

以下将起作用:

switch (a) {
    case "1":
         .....

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章