Conditionals for verification

1

I am creating a file js with a jquery . In this file I need to do a conditional or several conditionals that check a certain amount of numbers. If the variable x is one of the 1,3,5,6,7,9,10 numbers, you should display the word Yes , but if the numbers are 2,4,8,11,12,17 , you should display the word in>. How can I do this?

    
asked by anonymous 21.11.2014 / 13:57

3 answers

3

Use the jQuery $ .inArray () function

var sim = [1, 3, 5, 6, 7, 9, 10];
var nao = [2, 4, 8, 11, 12, 17];

var x = 2;

if ($.inArray(x, sim) != -1) {
  document.write('sim');  
} else if ($.inArray(x, nao) != -1) {
  document.write('nao');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
21.11.2014 / 14:02
3

You can use .indexOf () , you do not need jQuery. If you are going to repeat this check several times you can do a function for this.

I suggest storing these numbers in arrays:

var numerosA = [1,3,5,6,7,9,10];
var numerosB = [2,4,8,11,12,17];

and then check the new number with these:

numerosA.indexOf(1) != -1 // true
numerosA.indexOf(2) != -1 // false
numerosB.indexOf(1) != -1 // false
numerosB.indexOf(2) != -1 // true

The .indexOf () gives the position of that number inside of the array. If the number does not exist in the array it will give -1 .

You can also use a ternary for this. In this case you could do:

var resultado = numerosA.indexOf(seuNumero) != -1 ? 'Sim' : 'Não';

Example applied to a function , in this example giving a third answer for erroneous cases:

var numerosA = [1, 3, 5, 6, 7, 9, 10];
var numerosB = [2, 4, 8, 11, 12, 17];

function verificar(nr) {
    if (numerosA.indexOf(nr) != -1) return 'Sim!';
    else if (numerosB.indexOf(nr) != -1) return 'Não!';

    return 'Não existe em nenhuma...';
}

alert(verificar(1)); // Sim!
alert(verificar(2)); // Não!
alert(verificar(500)); // Não existe em nenhuma...
    
21.11.2014 / 14:01
1

If you prefer a solution in JQuery, you can use $ .inArray ()

if ($.inArray(x, [1,3,5,6,7,9,10]) !== -1){
    console.log('Sim');
}else if($.inArray(x, [2,4,8,11,12,17]) !== -1){
    console.log('Não');
}
    
21.11.2014 / 14:01