【问题标题】:Javascript switch(true) executes false statements?Javascript switch(true) 执行错误语句?
【发布时间】:2019-11-02 16:52:51
【问题描述】:

我循环遍历一组坐标值并对坐标进行数学运算以查看计算的值是否在哈希图中。如果它们在哈希图中,那么我想运行一个附加函数。因为我有多个案例,我想检查集合中的每个坐标,所以我认为使用 switch 语句来替换我的 if 语句会很酷,这样我的所有检查都可以在视觉上和逻辑上进行分组。当我用 switch 替换 if 语句时,我的代码返回了错误的结果。当我调试时,我意识到即使 case 为 false,switch 语句有时也会执行(我添加了 console.logs 来输出相同 switch 条件的结果,它会打印 false,但应该只在 true 时运行)。这是一个小例子:

var idm = {0:1, 3:1, 9:1, 10:1, 11:1, 12:1, 20:1, 21:1, 23:1}

var findNeighbors = function(b) {

    var u,d,l,r,lRow,rRow;
    var currentBuilding = parseInt(b);
    var currRow = Math.floor(currentBuilding/column);

    //remove value from map so we dont recount it.
    delete idm[currentBuilding];

    u = currentBuilding - column;
    d = currentBuilding + column;
    l = currentBuilding - 1;
    lRow = Math.floor(l/column);
    r = currentBuilding + 1;
    rRow = Math.floor(r/column);

    console.log("current idx:" + currentBuilding);
    console.log("u:" + u + ", d:" + d + ", l:" + l + " r:" + r);
    // debugger;
    switch(true) {
      case (idm.hasOwnProperty(u) === true):
        console.log((idm.hasOwnProperty(u)));
        console.log("map has " + currentBuilding + " -> u: " + u);
        findNeighbors(u);
      case (idm.hasOwnProperty(d) === true):
        console.log((idm.hasOwnProperty(d)));
        console.log("map has " + currentBuilding + " -> d: " + d);
        findNeighbors(d);
      case (lRow === currRow && idm.hasOwnProperty(l) === true):
        console.log((lRow === currRow && idm.hasOwnProperty(l)));
        console.log("map has " + currentBuilding + " -> l: " + l);
        findNeighbors(l);
      case (rRow === currRow && idm.hasOwnProperty(r) === true):
        console.log((rRow === currRow && idm.hasOwnProperty(r)))
        console.log("map has " + currentBuilding + " -> r: " + u);
        findNeighbors(r);
    }
    console.log("---------------------------");
  }

【问题讨论】:

  • 在每个 case 之后都需要 break 语句。不是吗?

标签: javascript hashmap switch-statement


【解决方案1】:

我认为使用 switch 语句来替换我的 if 语句会很酷,这样我的所有检查都可以在视觉和逻辑上进行分组。

好吧,编写有效的代码而不是看起来很酷的代码。您忘记了break 语句,因此执行流程fell through - 在第一个匹配之后没有评估其他case 表达式。顺便说一句 switching 常量是一种可怕(不酷)的做法。

改用标准的if/else

【讨论】:

  • 搞笑! @Bergi
  • 好吧,switch 被误用了两种方式,另一种则忽略了defaultswitch,在我工作过的每一种语言中,都是我可靠的朋友——当我 break 并且总是有一个 default 时。
  • @radarbob 当您不想在其中做任何事情时,可以忽略 default 的情况。
  • 天啊。无语。目瞪口呆。
猜你喜欢
  • 1970-01-01
  • 2019-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-27
  • 1970-01-01
相关资源
最近更新 更多