2015-12-06 3 views
-2

Есть ли способ сделать условное утверждение ниже короче? Существует много повторений, как вы можете увидеть:js - сокращать условное заявление

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 
    } 

} 

Спасибо вам

+2

Да, есть люди, в [Обзор кода] (http://codereview.stackexchange.com/), или даже на [сайте для гольфа] (http://codegolf.stackexchange.com/) для фанки решения, несомненно, помогут вам. – adeneo

+1

Перед публикацией обязательно проверьте их [руководство по отправке] (http://codereview.stackexchange.com/help/how-to-ask). –

+0

ОК. Спасибо - не знал раздел обзора кода. – Wasteland

ответ

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... все еще нуждается в любви, но это только возиться с индексом математике.

Смежные вопросы