Make an "or" inside the key of an attribute in JS

7

I have the following code:

scope.cm = 1;
scope.mm = 2;
scope.km = 3;


    tipoDeMedida[scope.cm || scope.mm || scope.km] = function(arrayQualquer){
          //executo meu bloco de código X.
    }

    tipoDeMedida[scope.km](arrayQualquer)

I'm getting the following error output:

    tipoDeMedida[scope.km] is not a function

From what I understand, in the function of the first block of code, you are not accepting the OR operator for each type of data I am trying to pass. I would like to know if there is any elegant way to solve this problem without having to do a function for each data type (I do not want to execute block X three times).

    
asked by anonymous 24.02.2017 / 18:29

1 answer

2

This does not work for the following reason

  • When evaluating the expression [scope.cm || scope.mm || scope.km] , the first value is considered valid, then the others are not evaluated.

See a test here: link

It would have to do for each value, as in the code below.

<div id="painel"> </div>
<hr>
<div id="funcoes"> </div>

<script>
    function Exibir( p_Param )
    {
        var painel = document.getElementById('painel');
        painel.innerHTML += p_Param+'<br>';
    }

    var mm = 1, cm = 2, dm = 3;
    var Medida = [];
    Medida[mm] = function( p_Param ){ Exibir('Medida: '+p_Param); }
    Medida[cm] = function( p_Param ){ Exibir('Medida: '+p_Param); }
    Medida[dm] = function( p_Param ){ Exibir('Medida: '+p_Param); }
    Medida[cm](cm);

    var g = 1, k = 2, t = 3, x = 4, y = 5;
    var Peso = [];
    Peso[ g || m || t || x || y ] = function( p_Param ){ Exibir('Peso: '+p_Param); }
    Peso[g](x);

    var funcoes = document.getElementById('funcoes');
    funcoes.innerHTML += 'Medida[cm] '+typeof(Medida[cm])+'<hr>';
    funcoes.innerHTML += 'Peso[g] '+typeof(Peso[g])+'<hr>';
    funcoes.innerHTML += 'Peso[m] '+typeof(Peso[m]); // Não executa
</script>

The result is:
Medida: 2  
Peso: 4  
Medida[cm] function  
Peso[g] function
    
24.02.2017 / 19:44