×

# 使用表驱动法替代普通的判断分支语句(JS的深入探索)

### 二、数组中的应用

#### 使用if else

``````function iGetMonthDays(iMonth) {
let iDays;
if(1 == iMonth) {iDays = 31;}
else if(2 == iMonth) {iDays = 28;}
else if(3 == iMonth) {iDays = 31;}
else if(4 == iMonth) {iDays = 30;}
else if(5 == iMonth) {iDays = 31;}
else if(6 == iMonth) {iDays = 30;}
else if(7 == iMonth) {iDays = 31;}
else if(8 == iMonth) {iDays = 31;}
else if(9 == iMonth) {iDays = 30;}
else if(10 == iMonth) {iDays = 31;}
else if(11 == iMonth) {iDays = 30;}
else if(12 == iMonth) {iDays = 31;}
return iDays;
}
``````

#### 使用表驱动(包括闰年判断)

``````const monthDays = [
[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
[31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
]
function getMonthDays(month, year) {
let isLeapYear = (year % 4 === 0) && (year % 100 !== 0 || year % 400 === 0) ? 1 : 0
return monthDays[isLeapYear][(month - 1)];
}
console.log(getMonthDays(2, 2000))
``````

### 三、对象中的应用

``````if (key = "Key A")
{
处理 Key A 相关的数据。
}
else if (key = "Key B")
{
处理 Key B 相关的数据。
}
``````

``````if (key = "Key A")
{
执行 Key A 相关的行为。
}
else if (key = "Key B")
{
执行 Key B 相关的行为。
}
``````

``````let table = {
A: {
data: "数据1",
action: "行为1"
},
B: {
data: "数据2",
action: "行为2"
}
}

function handleTable(key) {
return table[key]
}
console.log(handleTable('A').data)
``````

``````let table = {
A: {
data: "数据1",
action () {
console.log('action 1')
}
},
B: {
data: "数据2",
action () {
console.log('action 2')
}
}
}

function handleTable(key) {
return table[key]
}
handleTable('A').action()
``````

``````let vm = this
bdkq () {
window.clLib.localStorageOperating.updateData('default_hospital_code', '871978')
vm.\$router.push('/hospital')
},
etyy () { vm.goSp(10012) },
szn () { vm.goCh('szn') }
}
``````

``````switch (data.key) {
case 'bdkq':
window.clLib.localStorageOperating.updateData('default_hospital_code', '871978')
this.\$router.push('/hospital')
break
case 'etyy':
this.goSp(10012)
break
case 'szn':
this.goCh('szn')
break
default: