场景
const title = 0;
if (title == 1) {
console.log(1);
}else if(title == 2){
console.log(2);
}else if(title == 3){
console.log(3);
}else if(title == 4){
console.log(4);
}
………………
switch (title) {
case 1:
console.log(1);
break;
case 2:
console.log(2);
break;
case 3:
console.log(3);
break;
case 4:
console.log(4);
break;
}
……
优化
const actions = {
1: [1, 11],
2: [2, 22],
3: [3, 33],
4: [4, 44],
}
if (actions[title]) {
console.log(actions[title][0]);
alert(actions[title][1]);
}
//es6 Map方法
const actions = new Map([
[1, [1, 11]],
[2, [2, 22]],
[3, [3, 33]],
[4, [4, 44]],
['default', [0, '00']]
])
const myfunction = (title) => {
let action = actions.get(title) || actions.get('default')
console.log(action[0])
console.log(action[1])
}
myfunction(title)
网友评论