一、定義
表驅(qū)動方法(Table-Driven Approach)是一種使你可以在表中查找信息高帖,而不必用很多的邏輯語句(if或case)來把它們找出來的方法。事實上,任何信息都可以通過表來挑選茉兰。在簡單的情況下,邏輯語句往往更簡單而且更直接欣簇。
簡單講是指用查表的方法獲取值规脸。 我們平時查字典以及念初中時查《數(shù)學用表》找立方根就是典型的表驅(qū)動法坯约。在數(shù)值不多的時候我們可以用邏輯語句(if 或case)的方法來獲取值,但隨著數(shù)值的增多邏輯語句就會越來越長,此時表驅(qū)動法的優(yōu)勢就顯現(xiàn)出來了。(百度百科)
二莫鸭、數(shù)組中的應用
假設你需要一個可以返回每個月中天數(shù)的函數(shù)(為簡單起見不考慮閏年)
使用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;
}
使用表驅(qū)動(包括閏年判斷)
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 相關的數(shù)據(jù)。
}
else if (key = "Key B")
{
處理 Key B 相關的數(shù)據(jù)黔龟。
}
或
if (key = "Key A")
{
執(zhí)行 Key A 相關的行為妇智。
}
else if (key = "Key B")
{
執(zhí)行 Key B 相關的行為。
}
可以改裝成:
let table = {
A: {
data: "數(shù)據(jù)1",
action: "行為1"
},
B: {
data: "數(shù)據(jù)2",
action: "行為2"
}
}
function handleTable(key) {
return table[key]
}
console.log(handleTable('A').data)
或
let table = {
A: {
data: "數(shù)據(jù)1",
action () {
console.log('action 1')
}
},
B: {
data: "數(shù)據(jù)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
}
四蛋欣、總結(jié)
好的代碼總是將復雜的邏輯以分層的方式降低單個層次上的復雜度航徙。復雜與簡單有一個相互轉(zhuǎn)化的過程。(CSDN)