首页 > 解决方案 > 如何退出我的 switch 语句?

问题描述

我的尝试:

const find = function (map, type) {

let location = [];

for(var i = 0; i < map.length; i++){
    for(var j = 0; j < map[i].length; j++){
        switch(true) {
            case (type === 'gold' && map[i][j] === 'R' ):
                location.push(j,i);
                break;
            case (type === 'silver' && (map[i][j] === 'S' || map[i][j] === 'R')):
                location.push(j,i);
                break;
            case (type === 'bronze' && (map[i][j] === 'S' || map[i][j] === 'R' || map[i][j] === 'M' ) ):
                location.push(j,i);
                break;
            default:
                return 'false';
                break;
        }
    }

}

return location;
};
console.log(find(
    [
        // COLUMNS ARE X
        // 0    1    2    3    4    5
        ['s', 'R', 's', 'S', 'n', 'M'], // 0 ROWS ARE Y
        ['s', 'M', 's', 'S', 'r', 'M'], // 1
        ['s', 'M', 's', 'R', 'r', 'm'], // 2
        ['S', 'r', 's', 'm', 'r', 'M'], // 3
        ['S', 'r', 's', 'm', 'r', 'M'], // 4
        ['S', 'r', 'S', 'M', 'M', 'S']  // 5
    ],
    'gold'
));

我基本上是遍历一个表示矿物地图的二维数组,并通过将索引记录到数组位置并返回它来返回与我的 switch 语句中的条件相匹配的第一块土地的坐标。

我有两个主要问题:

我如何对其进行编码,以便在找到与我的案例条件匹配的第一块土地后立即终止循环?现在 JS 将继续循环遍历整个 2D 数组,推入更多我不想要的坐标。

如果没有找到任何东西,我希望 JS 简单地返回字符串 False 。但是,即使 case 语句的计算结果为 True,这似乎也在发生。只是想知道我是否有某种错字?

标签: javascriptarraysswitch-statement

解决方案


布尔值不是 switch 语句的理想用例 -

switch(true)- 参数应该接受一个变量。您正在传递一个常量变量。该变量应与 case 语句匹配。

, 的正确用法switch(bool)应该是

var myBool = getValue();
switch(myBool) {
  case true:
    console.log('true');
    break;
  case false:
    console.log('false');
    break;

对于逻辑,我建议一个if/else

            if (type === 'gold' && map[i][j] === 'R' ){
              location.push(j,i);
            } else if (type === 'silver' && (map[i][j] === 'S' || map[i][j] === 'R')){
              location.push(j,i);
            } else if (type === 'bronze' && (map[i][j] === 'S' || map[i][j] === 'R' || map[i][j] === 'M' ) ) {
              location.push(j,i);
            }

推荐阅读