簡體   English   中英

如何干掉這段代碼(if else 語句)

[英]How to DRY up this code (if else statement)

讓這段代碼更干的最好方法是什么? 我正在考慮在 currentRoom.id 相同的地方嵌套 if 語句,或者只是通過添加 || 來壓縮它條件內的部分。 但我不確定這些解決方案是否使代碼更整潔。

這種東西最合理最簡潔的風格是什么?

if(direction === 'east' && player.currentRoom.id === 1) {
          roomNum = '3';
        } else if (direction ==='east' && player.currentRoom.id === 4) {
          roomNum = '1';
        } else if (direction === 'west' && player.currentRoom.id === 1) {
          roomNum = '4';
        } else if (direction === 'west' && player.currentRoom.id === 3) {
          roomNum = '1';
        } else if (direction === 'north' && player.currentRoom.id === 5) {
          roomNum = '1';
        } else if (direction === 'north' && player.currentRoom.id === 1) {
          roomNum = '2';
        } else if (direction === 'south' && player.currentRoom.id === 1) {
          roomNum = '5';
        } else if (direction === 'south' && player.currentRoom.id === 2) {
          roomNum = '1';
        }
}

房間的數組為 arrays 意味着您只需添加/減去當前的 X 或 Y 坐標。 就像是:

 const rooms = [ [0, 2,0], [4, 1, 3], [0, 5, 0], ]; let horizIndex = 1; let vertIndex = 1; console.log(rooms[vertIndex][horizIndex]); const changeRoom = (x, y) => { if (rooms[vertIndex + y][horizIndex + x]) { horizIndex = horizIndex + x; vertIndex = vertIndex + y; console.log('entered', rooms[vertIndex][horizIndex]); } else { console.log('Invalid room'); } }; const direction = 'south'; if (direction === 'south') { changeRoom(0, 1); } else if (direction === 'north') { changeRoom(0, -1); } else if (direction === 'east') { changeRoom(1, 0); } else if (direction === 'west') { changeRoom(-1, 0); }

在沒有任何其他程序重構的情況下,您可以通過遍歷由每個子句中的變量數據組成的元組數組來壓縮示例中的重復語法,並在第一個可能的匹配項之后中斷:

for (const [dir, id, num] of [
  ['east',  1, '3'],
  ['east',  4, '1'],
  ['west',  1, '4'],
  ['west',  3, '1'],
  ['north', 5, '1'],
  ['north', 1, '2'],
  ['south', 1, '5'],
  ['south', 2, '1'],
]) {
  if (direction === dir && player.currentRoom.id === id) {
    roomNum = num;
    break;
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM