Is there a "in" comparator operator in Javascript?

Asked

Viewed 253 times

9

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

A visual example:

if (tipoDemissao in [1, 2, 5]){
    valorDemissao = 525.20;
}
  • 1

    There is, but it’s for checking properties on an object: in - MDN

  • 3

    Based on your code I think you can do with an index of a look at this jsfiddle

3 answers

11


In version Ecmascript 2016 (ES7) you can use .includes() which is what you’re looking for for lists/arrays.

In this case the method returns a boolean:

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

On objects, as you mentioned there is the in, to check object properties.

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

Or you can use it too .hasOwnProperty('foo'), that shows only instance properties.

In strings and also arrays there’s the indexOf() like the @Maniero indicated. Here the method returns the position of what was searched for in Array or String. If the result is >= 0 then it is because there is.

  • 2

    @durtto it is only good to clarify that use this will only work in browsers that support this feature, the others will fail.

7

No. You need to use a trick, create a function, or use a library. Example:

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

If I may use jQuery has:

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

Now that it’s all worn browsers modern can already be interesting to use a new function that gives what awaits:

if ([1, 2, 5].includes(tipoDemissao)) valorDemissao = 525.20;

If this doesn’t fully resolve what you want, the solution is to create a function contains() to treat everything the way you need to.

I put in the Github for future reference.

  • contains can only be done in text, "olá mundo".contains('mundo') => true

  • That’s why I said I’d have to create a.

  • 3

    What I meant was, create a function contains can give rise to confusion, since it already exists string.contains - other than that, top notch response :)

5

Depending on the scenario it can be interesting to do this, by providing 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");
    }
}

Browser other questions tagged

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