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

Asked

Viewed 130 times

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 that I am trying to pass on. I wonder if there is some elegant way to solve this problem without having to do a function for each type of data(I don’t want to run block X three times).

  • I don’t quite understand what you want to do, but if you do var tipoMedida = function(tipo, arrayQualquer) and pass as tipoMedida(scope.km, arrayQualquer) doesn’t solve?

  • It does... I’ll even do it. I only asked because the pattern of the system in question is the one that I showed, so you will have to refactor a lot in this solution.But I wanted to understand why he is not recognizing the other values....

  • Ah, yes, it doesn’t work because ||(or) is Boolean, is 1, 2 or 3, and other languages that would generate a true, but from what I’ve seen js tend to use only the first value informed, possibly you would have only the cm

  • got it... you’re right! I tested it here and that’s exactly what’s going on. The value of Scope.cm will always exist, so it will never fall into the next condition....

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: http://codepen.io/rmagalhaess/pen/bqNVQE?editors=1010

It would have to do for every 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.