这是在矩形网格上绘制点(在其他位置生成)的程序的一部分。如果该点落在网格之外(索引<0或索引> grid_length),则将修改索引以将其放置在网格内。我已经做到了3种方式,
我尝试了功能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
答案 0 :(得分:0)
switch
语句计算expression,将表达式的值与case
子句匹配,并执行与该{{ 1}},以及case
之后匹配case
之后的语句。
这意味着您不能将表达式放在case
子句中。只是价值观。如您在statements上的示例所见。