日常項目開發我們必然且高頻會遇到判斷場景
比如:
一個管理系統,根據用戶特徵每人發放福利
1,瘸子 === 送 === 輪椅
2,瞎子 === 送 === 墨鏡
3,聾子 === 送 === 耳機(程序員邏輯)
4,孩子 === 送 === 玩具
5,男子 === 送 === 啤酒
6,女子 === 送 === 炸雞
6個簡單的條件,不太深層,但很好理解
首先 使用 if else 解決:
let client = "";//結果
let type = "瘸子";//客戶
if(type === "瘸子")
return client = '輪椅';
else if(type === "瞎子")
return client = '墨鏡';
else if(type === "聾子")
return client = '耳機';
else if(type === "孩子")
return client = '玩具';
else if(type === "男子")
return client = '啤酒';
else if(type === "女子")
return client = '炸雞';
console.log(client);
使用switch case 試下
let client = "";//結果
let type = "瘸子";//客戶
switch (type) {
case '瘸子':
client = '輪椅';
break;
case '瞎子':
client = '墨鏡';
break;
case '聾子':
client = '耳機';
break;
case '孩子':
client = '玩具';
break;
case '男子':
client = '啤酒';
break;
case '女子':
client = '炸雞';
break;
default:
client = '';
break;
}
以上是傳統判斷寫法,沒有多高級,也沒有很優雅,唯一一點 switch case 比起if else 更加清晰,代碼整潔一些。但是代碼很長,這時候我們就要像一些其他方法,比如利用對象數組的一些特性
created() {
// 先利用對象的特性
// 進來一個瘸子
let type = '瘸子';
const clientObj = {
'瘸子': '輪椅',
'瞎子': '墨鏡',
'聾子': '耳機',
'孩子': '玩具',
'男子': '啤酒',
'女子': '炸雞',
};
let client = clientObj[type]
},
代碼瞬間高檔起來,並且十分優雅
在這裏插入代碼片