How to compare variables using Javascript?

Asked

Viewed 1,831 times

4

I use a lot of variable comparison. Example:

 if (item[l].item[0] == 'tipoRescisao') {
                log.info('Tipo Rescisão: ' + item[l].item[1])
                if (
                    (item[l].item[1] == (1))
                        || (item[l].item[1] == 01)
                        || (item[l].item[1] == 08)
                        || (item[l].item[1] == 10)
                        || (item[l].item[1] == 12)
                        || (item[l].item[1] == 13)
                    ) {
                    prazo = dataDesligamento + 24;
                }
            }

There is another way to make these comparisons more succinctly?

  • What you specifically want to know is to compare the variable with multiple values?

  • that’s right, I want to know if a variable is in a certain range of values.

  • Has two q is the same value, has some reason for it?

  • No, you can ignore

3 answers

6

I believe the easiest way would be to search in a array of the values to be compared. If array is because the variable is worth at least one of these values. There are people who even have some function to abstract it.

if ([1, 8, 10, 12, 13].indexOf(item[l].item[1]) > -1) {
    prazo = 20;
}

var prazo = 0;
var x = 8;
if ([1, 8, 10, 12, 13].indexOf(x) > -1) prazo = 20;
console.log(prazo);
var prazo = 0;
var x = 7;
if ([1, 8, 10, 12, 13].indexOf(x) > -1) prazo = 20;
console.log(prazo);

I put in the Github for future reference.

  • We think the same, but it took me two minutes longer :D

5


You can make this type of checking simpler by using indexOf.

first create a array as all the possibilities you want.

['1', '01', '08', '10', '12', '13']

After just check if the value you are looking for is inside this array through the indexOf

['1', '01', '08', '10', '12', '13'].indexOf(item[l].item[1])

If the result found is -1 then the value does not exist in the array research.

So yours if would be :

// Função simples
function inArray(value, array){
  return array.indexOf(value) != -1;
}

console.log(inArray('01', ['01', '10']));

// Aplicada ao prototype de string
String.prototype.inArray = function(array){
  return inArray(this.toString(), array);
}

console.log('01'.inArray(['01', '10']));

  • Can help me to create a function, since I use these comparisons a lot?

  • @durtto be now, if it eases a little.

  • +1 If the result found is -1 then the value does not exist in the search array

-1

You will need to check which type of value item[l].item[1].

Type string: If it’s "01," you’ll have to do it this way

if(valor item[l].item[1] === "01")...

Type Int: If it’s 1, you’ll have to do it this way

if(valor item[l].item[1] === 1)...
  • 2

    Your answer doesn’t help me, it doesn’t answer the question.

Browser other questions tagged

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