Is there comparator operator "in" in JavaScript?

6

In JavaScript is there a way to use in to check if the value of a variable is contained in a list of values?

A visual example:

if (tipoDemissao in (1,2,5)){
    valorDemissao = 525.20;
}
    
asked by anonymous 12.04.2016 / 14:25

3 answers

7

In ES6 you can use .includes() that is what you are looking for lists / arrays.

In this case the method returns a Boolean:

[1, 2, 3].includes(2); // true
[1, 2, 3].includes(9); // false

In Objects , as you mentioned there is in , to check properties of objects.

'foo' in {foo: 'bar'} // true
'so' in {foo: 'bar'} // false

Or you can also use .hasOwnProperty('foo') , which shows only instance properties.

In Strings and also Arrays there is indexOf() like @bigown specified . Then the method returns the position of what was searched for in the Array or String. If the result is >= 0 then it is because it exists.

    
12.04.2016 / 18:04
7

Does not exist. You need to use some trick, create a function, or use a library. Example:

if ([1, 2, 5].indexOf(tipoDemissao) > -1) {
    valorDemissao = 525.20;
}

If you can use jQuery has:

if ($.inArray(tipoDemissao, [1, 2, 5])) {
    valorDemissao = 525.20;
}

If this does not fully resolve what you want, the solution is to create a contains() function that handles everything the way you need it.

    
12.04.2016 / 14:35
3

Depending on the scenario, it may be interesting to do this, because it provides more possibilities:

var listaDeNumeros = [2,4,6,8,10];
var numeroAhProcurar = 6;

for(numero in listaDeNumeros){
    if (numeroAhProcurar == listaDeNumeros[numero]){
        alert("Numero " + listaDeNumeros[numero] + " encontrado");
    }
}
    
12.04.2016 / 16:47