Home > Mobile >  How do I approach variable with string value?
How do I approach variable with string value?

Time:01-13

I like to pass parameter and want to use it to return specific variable

test1 (type) {
    const enable { color: 'blue' }
    const disabled { color: 'red' }
    return type === 'enable' ? enable : disabled
}

so for example, i like to change test1 to test2. I want to do this because I have mulitple type and it makes code complicated. Is there any way that i can do this?

test2 (type) {
    const enable { color: 'blue' }
    const disabled { color: 'red' }
    return type
}

CodePudding user response:

Use an object keyed by the type value.

function test2(type) {
    const vals = {
        enable: { color: 'blue' },
        disable: { color: 'red' }
    };
    return vals[type];
}

CodePudding user response:

You can write something like follows

test2 (type) {
    switch(type) {
        case 'enable':
            return { color: 'blue' }
        case 'disabled':
            return { color: 'red' }
    }
}
  • Related