一、定義
表驅動方法(Table-Driven Approach)是一種使你可以在表中查找信息,而不必用很多的邏輯語句(if或case)來把它們找出來的方法。事實上,任何信息都可以通過表來挑選。在簡單的情況下,邏輯語句往往更簡單而且更直接。
簡單講是指用查表的方法獲取值。 我們平時查字典以及念初中時查《數學用表》找立方根就是典型的表驅動法。在數值不多的時候我們可以用邏輯語句(if 或case)的方法來獲取值,但隨著數值的增多邏輯語句就會越來越長,此時表驅動法的優勢就顯現出來了。(百度百科)
二、數組中的應用
假設你需要一個可以返回每個月中天數的函數(為簡單起見不考慮閏年)
使用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
let adTable = {
bdkq () {
window.clLib.localStorageOperating.updateData('default_hospital_code', '871978')
vm.$router.push('/hospital')
},
etyy () { vm.goSp(10012) },
szn () { vm.goCh('szn') }
}
adTable[data.key] ? adTable[data.key]() : location.href = data.ad_url
以前是怎么寫的呢? 看看就知道了,特別復雜!
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:
location.href = data.ad_url
break
}
四、總結
好的代碼總是將復雜的邏輯以分層的方式降低單個層次上的復雜度。復雜與簡單有一個相互轉化的過程。(CSDN)