javascript switch语句无法返回正确的值

时间:2020-08-01 08:39:57

标签: javascript switch-statement line-numbers

这是在矩形网格上绘制点(在其他位置生成)的程序的一部分。如果该点落在网格之外(索引<0或索引> grid_length),则将修改索引以将其放置在网格内。我已经做到了3种方式,

  1. 常规js代码:函数get_bounded_index():这可以正常工作
  2. 三元语句: function ternary():可以正常工作
  3. switch语句: function switch_statement():失败。

我尝试了功能switch_statement(),无论是否带有 grid_length 参数,都无济于事。 很抱歉缺少行号,无法解决。 另外,控制台指示的行号大于我的文件的长度。这与我编写的其他JS文件间歇地发生。我也对此感到困惑。 您能告诉我我要去哪里了吗?

function get_bounded_index(index) {
    bounded_index = index;
    if (bounded_index < 0) {
      bounded_index = index + grid_length;
    }
    if (bounded_index >= grid_length) {
      bounded_index = index - grid_length;
    }
    return bounded_index;
  }

  function ternary(index) {
    bounded_index = index;
    bounded_index < 0 ? bounded_index = index + grid_length : bounded_index = index - grid_length;
    return bounded_index;
  }

  function switch_statement(index, grid_length) {
    bounded_index = index;
    switch (index) {
      case (index < 0):
        bounded_index === index + grid_length;
        break;
      case (index > grid_length):
        bounded_index === index - grid_length;
        break;
    }
    return bounded_index;
  }

  let grid_length = 100;
  console.log(get_bounded_index(-10)); // 90 ok
  console.log(get_bounded_index(110)); // 10 ok
  console.log("__________");
  console.log(ternary(-10)); // 90 ok
  console.log(ternary(110)); // 10 ok
  console.log("__________");
  console.log(switch_statement(-10, grid_length )); // -10 implies grid_length = 0
  console.log(switch_statement(110, grid_length)); // 110 implies grid_length = 0

1 个答案:

答案 0 :(得分:0)

switch语句计算expression,将表达式的值与case子句匹配,并执行与该{{ 1}},以及case之后匹配case之后的语句。

这意味着您不能将表达式放在case子句中。只是价值观。如您在statements上的示例所见。