讓這段代碼更干的最好方法是什么?我正在考慮在 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';
}
}
uj5u.com熱心網友回復:
在沒有任何其他程式重構的情況下,您可以通過回圈遍歷由每個子句中的變數資料組成的元組陣列來壓縮示例中的重復語法,并在第一次潛在匹配后中斷:
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;
}
}
uj5u.com熱心網友回復:
擁有一組房間陣列意味著您只需添加/減去當前的 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);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/512670.html
標籤:javascriptif 语句干燥
