dimanche 4 août 2019

If-else condition in JavaScript more dynamic

I have a JavaScript code which has many if-else conditions for different brands w.r.t html

function get_brand_label(b) {
    var brand1label = '<div class="brand1_label">B1</div>';
    var brand2label = '<div class="brand2_label">B2</div>';
    var brand3label = '<div class="brand3_label">B3</div>';
    var brand4label = '<div class="brand4_label">B4</div>';

    if (b == 'Brand1') {
        return brand1label;
    } else if (b == 'Brand2') {
        return brand2label;
    } else if (b == 'Brand3') {
        return brand3label;
    } else if (b == 'Brand4') {
        return brand4label;
    }
}

I am using this get_brand_label function in another function as:

var label = get_brand_label(d.brand);

In future, if I want to add B5 and B6, I need to add new if-else conditions

So before adding new brands, is there any way to make the above existing code more dynamic so that I don't need to add if-else conditions in future while adding new brands

Aucun commentaire:

Enregistrer un commentaire