js - 缩短条件陈述

时间:2015-12-06 19:03:13

标签: javascript if-statement

有没有办法让下面的条件语句更短?你可以看到有很多重复:

containment

并且detectWall函数供参考:

var searchArea = function() {
    // Search the area around the current position for hidden doors
    if(detectWall('left') == 2) {
        status.innerHTML = "Hidden Door to the left";
    } else if (detectWall('right') == 2) {
        status.innerHTML = "Hidden door to the right";
    } else if (detectWall('up') == 2) {
        status.innerHTML = "Hidden door above you";
    } else if (detectWall('down') == 2) {
        status.innerHTML = "Hidden door below you";
    } else if (detectWall('right') == 3 || detectWall('left') == 3 || detectWall('up') == 3 || detectWall('down') == 3) {
        status.innerHTML = "You are close to the fountain";
    }


}

谢谢

1 个答案:

答案 0 :(得分:0)

这是一个让它更通用的想法:

var wallDetectorBase = [

    "left": { 
        incY: 0,
        incX: -20,
        hasWall: 2,
        msg: "Hidden Door to the left"
    },
    "right": {
        dir: "right",
        incY: 0,
        incX: 20,
        hasWall: 2,
        msg: "Hidden door to the right"
    },

现在,您可以对左侧和右侧进行迭代,并将整个逻辑组合在一起:

for ( var n = 0; n < wallDetectorBase.length; n++ )
{
   if ( mapArray[parseInt((player.y + wallDetectorBase[n].incY ...]... == wallDetectorBase[n].hasWall )
   status.innerHTML = wallDetectorBase[n].msg;

显然,mapArray[parseInt((pl...部分仍然需要一些爱,但这只是摆弄索引数学。