la programación basada en tablas

Una pluralidad de código si ... si no ... estructura, optimización de la programación basada en tablas.
Por ejemplo:


优化前:
howManyDays(year, month){
    if(month === 1 ||
        month === 3 ||
        month === 5 ||
        month === 7 ||
        month === 8 ||
        month === 10 ||
        month === 12
    ){
        return 31
    }else if(month === 2){
        return isLeapYear(year) ? 29 : 28
    }else{
        return 30
    }
}

优化后:
howManyDays(year, month){
    const table = {
        1: 31, 3: 31, 5: 31, 7: 31, 8: 31, 10: 31, 12:31,
        4: 30, 6:30, 9: 30, 11: 30,
        2: isLeapYear(year) ? 29 : 28
    }
    return table[month]
}

优化前:
function calculateGrade(score){
    if(score>=90){
        return 'A'
    }else if(score >= 80){
        return 'B'
    }else if(score >= 70){
        return 'C'
    }else if(score >= 60){
        return 'D'
    }else {
        return 'E'
    }
}

优化后:
function calculateGrade(score){
    const table = {
        100: 'A', 
        90: 'A',
        80: 'B',
        70: 'C',
        60: 'D',
        others: 'E'
    }
    return table[Math.floor(score/10)*10] || table['others']
}

enlace Referencia : https: tipo //www.zhihu.com/search = contenido y q =% E9% A1% B9% E7% 9B% AE% E5% 89% 8D% E7% AB% AF% E4% BB% A3%? E7% A0% 81% E4% BC% 98% E5% 8C% 96

Publicado 80 artículos originales · ganado elogios 82 · Vistas a 10000 +

Supongo que te gusta

Origin blog.csdn.net/qq_42893625/article/details/103922079
Recomendado
Clasificación