break 導致貫穿錯誤,除錯困難。利用物件字面量將「鍵→行為」映射,查找替代分支判斷。
function testSwitch(name) {
switch (name) {
case '1': return 'hack';
case '2': return 'slash';
case '3': return 'run';
default: return false;
}
}
function testFn(name) {
const actions = {
'1': () => 'hack',
'2': () => 'slash',
'3': () => 'run'
};
if (typeof actions[name] !== 'function') return false;
return actions[name]();
}
// 測試
console.log(testSwitch('1'), testFn('2')); // "hack" "slash"
const commands = {
greet: (name) => `Hello, ${name}!`,
calc: (a, b) => a + b,
fetch: async (url) => (await fetch(url)).json()
};
function execute(cmd, ...args) {
if (typeof commands[cmd] !== 'function') throw new Error(`Unknown command: ${cmd}`);
return commands[cmd](...args);
}
execute('greet', 'World'); // "Hello, World!"
execute('calc', 1, 2); // 3
| 維度 | Switch | 命令物件 |
|---|---|---|
| 擴充性 | 修改原函數 | 新增屬性即可,符合 OCP |
| 可測試性 | 需測試整個分支 | 單獨測試各命令函數 |
| 動態載入 | 困難 | 可從配置/遠端動態註冊 |
| 程式碼組織 | 集中式 | 分散式,便於模組化 |
「良好的程式碼沒有 if/else/switch」——命令物件模式將條件分派轉為資料查找,符合 JavaScript 物件字面量與一級函數的語言特性,是重構條件邏輯的首選模式。