Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/385.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript js-缩短条件语句_Javascript_If Statement - Fatal编程技术网

Javascript js-缩短条件语句

Javascript js-缩短条件语句,javascript,if-statement,Javascript,If Statement,有没有办法缩短下面的条件语句?正如你所看到的,有很多重复: 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')

有没有办法缩短下面的条件语句?正如你所看到的,有很多重复:

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";
    }


}
和detectWall函数供参考:

 var detectWall = function(dir) {
    // Detect walls from the array
    switch(dir) {
        case 'right':
            return mapArray[parseInt(player.y/20)][parseInt((player.x+20)/20)]
        case 'left':
            return mapArray[parseInt(player.y/20)][parseInt((player.x-20)/20)]
        case 'up':
            return mapArray[parseInt((player.y-20)/20)][parseInt(player.x/20)]
        case 'down':
            return mapArray[parseInt((player.y+20)/20)][parseInt(player.x/20)]
        default:
            return false
    }

}

谢谢

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

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;
for(var n=0;n

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

是的,在上的人,甚至是在上的人,肯定会帮你解决问题。但是一定要在发布前检查他们的爱。好的。谢谢-不知道代码审查部分。我投票结束这个问题,因为代码c不包含任何问题,该问题更适合codereview.stackexchange.com。