Passing an Object to Switch Case Javascript

后端 未结 3 1954
北海茫月
北海茫月 2021-01-13 09:42

I wanted to have a switch/case statement that accepts an object in Javascript.

The function looks like this.

const validate = (values) => { valu         


        
相关标签:
3条回答
  • 2021-01-13 10:04

    const switchCase=(obj={},str='')=>obj[Object.keys(obj).find(ele=>ele.toString().split('|').includes(str.toString())) || 'default']
    
    
    console.log(switchCase({
       default:'o',
      40:'ko',
      xyz:'hi',
      'yi|th' :'ho'
    },'yi'))

    0 讨论(0)
  • 2021-01-13 10:15

    You are using it like a function parameter which is unnecessary (and wrong). Since switch statements check that the value equals the case, you'll want to use:

    switch(true) 
    
    0 讨论(0)
  • 2021-01-13 10:24

    Change

    switch(values) {
    

    To

    switch(true) {
    

    switch checks with strict equality.

    And use, if necessary some break if you do not want to fall through the switch cases (kudos to blex).

    0 讨论(0)
提交回复
热议问题