javascript - 如何退出我的 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,这似乎也在发生。只是想知道我是否有某种错字?
解决方案
布尔值不是 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);
}
推荐阅读
- delphi - 写入后 TFileStream 的 MD5 哈希不正确
- python - Python/美丽汤。url列表->解析->将数据提取到csv。错误
- autocomplete - Google Geocode/Places API:搜索邮政编码 - 获取与其相关的地址,可能吗?
- node.js - 我做错了什么?
- pandas - 如何在 pandas 数据框中将同名列合并为一个,以便所有列都是唯一的?
- maven-plugin - 使用 native-image-maven-plugin 构建 GraalVM 错误
- javascript - CesiumJS JSON - 描述图像从信息框中删除属性
- object - 为扩展 Pane 的类创建的对象在哪里?
- python - 使用糟糕的计算机进行迁移学习
- ionic-framework - Webview 在 Android KitKat - Ionic 4 中未正确呈现 CSS