switch case结构
function doAction(action) {
switch (action) {
case '20':
return 'enough';
case '10':
return 'not enough';
default:
return 'retry!'
}
}
let a = prompt('请输入数字:');
console.log(doAction(a));
对象加函数结构
function doAction(action){
let actions = {
'20': ()=>{
return 'enough';
},
'10': ()=> {
return 'not enough';
}
}
if (typeof actions[action] !== 'function') {
throw new Error('retry!');
}
return actions[action]();
};
let a = prompt('请输入数字:');
console.log(doAction(a));