简体   繁体   中英

Why I can't do with Switch-Case what I do with If-Else in JS?

Can you help about the JS DOM example below,

The if-else structure I specified in example 1 works, but the switch-case structure I specified in example 2 does not work. The switch-case structure does not work, although they both function the same. Why?

Thanks

--- Example 1 / Works ---

fontSizes.forEach(size => {
 
    size.addEventListener('click', () => {
      
        if(size.classList.contains('font-size-1')) {
            .....
        } else if (size.classList.contains('font-size-2')) {
            .....   
        }
        
    })
})

--- Example 2 / Doesn't work ---

fontSizes.forEach(size => {
 
    size.addEventListener('click', () => {
      
      switch (size.classList.contains) {
           case 'font-size-1': 
             ....
           break;
           case 'font-size-2': 
             ....
           break;
       }            
    })
})

You didn't use the switch properly, you're checking size.classList.contains which points to a function with strings (like font-size-1 ) instead of comparing the actual value.

You can use split (with the includes functions) or use size.classList.contains in each case

Take a look here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList/contains How to check className in a switch statement when an element has multiple classes

contains is a method.

So you can't use: switch(size.classList.contains){case 'class1':...}

Instead you should use if(size.classList.contains('class1')){}

If you want a more clean code, you can create an array (or object) for the cases and put if s on a loop.

Please not that they are not the same. In the first one you are calling function add taking the output whereas in the second one all you are passing via switch statement is the reference to function. The size.classlist.contains is a function which expects an argument. Please know the difference.

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