Alternative to the “switch” Statement

后端 未结 8 2055
眼角桃花
眼角桃花 2020-12-04 20:15

I do not want to use Switch in my code, so I\'m looking for some alternative

Example with Switch:

function write(what) {

  switch(w         


        
8条回答
  •  执笔经年
    2020-12-04 20:42

    I had to do do a compare for a group sort of object props for a list and did not want to do a switch/case for all the possibilities so I did an array of objects assignment to a numeric rank first so the case became a simple compare. This is only 4 possibilities but you get the drift of how to extend this to situation where a switch/case becomes unmanageable:

    function mySort2(item1,item2){

         var matrix = {  
        'repair': 4,  
        'r/r': 3,  
        'part': 2,  
        'misc': 1  
      };  
    
    (matrix[item1.category] < matrix[item2.category]) ? return +1 : return -1;
    

    // if possible bad data need to check for this first ???

    i1=matrix[item1.category] || null;
    i2=matrix[item2.category] || null;
    
    if (i1==null){
        // handle bad data in item 1
        return +1; // put it after 2
    }
    
    if (i2==null){
        // ditto 
        return -1; //put 1 first
    }
    
    if (i1

    }

提交回复
热议问题