【发布时间】: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