简体   繁体   中英

What would be the proper way to write this? Need to replace a switch statement

I'm looking for some better way to write this code, since it looks very ugly. But I guess it works right, but i'm just wondering if there's some better way to write this? Basically, every key inside the statement needs to check for a thing just related to that key. Maybe I should just write some big if statement? Or use some JSON Object and store the key name, and the name of the name inside the check? Would appreciate some pointers on the best way to do this!

and the code isn't the real code (don't have it right now), it's just something I wrote in quickly to give an example of how the real code look.

switch (key) {
case 'cat':
    if (animals.check('kitty')) {
        delete animalsArray[index];
    }
    break;
case 'dog':
    if (animals.check('doggo')) {
        delete animalsArray[index];
    }
    break;
case 'hippo':
    if (animals.check('idk')) {
        delete animalsArray[index];
    }
    break;
case 'tiger':
    if (animals.check('somethingSpecificforTIGER')) {
        delete animalsArray[index];
    }
    break;
case 'toad':
    if (animals.check('idk')) {
        delete animalsArray[index];
    }
    break;
case 'horse':
case 'zebra':
    if (animals.check('ass')) {
        delete animalsArray[index];
    }
    break;

default:
    break;
}

Just need to improve the code :P

Use an object that maps the key to the animals.check argument:

const mapping = {
    cat: "kitty",
    dog: "doggo",
    ...
};
if (mapping.hasOwnProperty(key) && animals.check(mapping[key])) {
    delete animalsArray[index];
}

Im not sure i get what you want but can't you use something like:

var zoo = {
    king : 'lion',
    thief : 'snake'
}

var arr = ['lion', 'snake'];

delete arr[arr.indexOf(zoo.king)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM