How to compare variables using JavaScript?

3

I use a lot of variables. 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;
                }
            }

Is there another way to make these comparisons more succinctly?

    
asked by anonymous 14.10.2016 / 15:36

3 answers

5

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

First create a array as all the possibilities you want.

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

After just checking that the value you are looking for is within this array through 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 search.

So your 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']));
    
14.10.2016 / 15:44
6

I believe the easiest way would be to search an array for the values to be compared. If it finds in the array it is because the variable is worth at least one of those 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);
    
14.10.2016 / 15:42
-1

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

Type string : if it is "01", you will have to do it this way

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

Type Int : if it is 1, you will have to do it this way

if(valor item[l].item[1] === 1)...
    
14.10.2016 / 15:43