Conditional for verification

Asked

Viewed 432 times

2

I’m Creating a File js with a jquery. In this file I need to make a conditional or several conditional that check a certain amount of numbers. If the variable x is one of the numbers 1,3,5,6,7,9,10, one must show the word Yes, but if the numbers are 2,4,8,11,12,17, one must show the word no. How can I do that?

  • 1

    Are these exactly the numbers that will show "Yes" and "No" or do they have any meaning behind the numbers? Also, why use jQuery to compare numbers? It couldn’t be done in pure javascript?

3 answers

4


Use the function $.inArray() jQuery

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>

3

You can use the .index(), You don’t need jQuery. If you are going to repeat this check several times you can do a function for this.

I suggest to store 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 .index() gives the position of that number within the array. If the number does not exist in the array, it will give -1.

You can also use a ternary for this. Then you can do:

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

Example applied to a function, in this example giving a third answer to 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...

  • 1

    Good answer. Using jQuery.inArray() for a simple thing seemed to kill ant with cannonball.

1

If you prefer a Jquery solution, 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');
}

Browser other questions tagged

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