Condition "if" does not enter

Asked

Viewed 123 times

1

Why does this type of condition not work in Javascript?

if (permissoes[0] || permissoes[5] || permissoes[10] || permissoes[15] || permissoes[20] || permissoes[25] || permissoes[30] || permissoes[35] == "0") {
                valorModulo1 = "0";
            } else {
                valorModulo1 = "1";
            }

That one array permissões always returns 0 or 1, I want if any element of these ai is 1 it returns valorModulo1 = "1" if all are zero returns valorModulo1="0", only when I change the value of array for 1 he does not enter the else.

  • Have you tried permissoes[0] == 1 ?

2 answers

4


I think this is what you want:

if (permissoes[0] == "0" && permissoes[5] == "0" && permissoes[10] == "0" && permissoes[15] == "0" && permissoes[20] == "0" && permissoes[25] == "0" && permissoes[30] == "0" && permissoes[35] == "0") {
    valorModulo1 = "0";
} else {
    valorModulo1 = "1";
}

There is an error that you are not comparing the values, except in the latter, and worse in Javascript has case that can work by coincidence and fool you.

But in addition to this if you read the specification you put in the question everyone should be 0 to give 0, well, it all means that they need to be linked with a And and not a OR that would allow only one to serve. So if one is false, everything will be false and fall into the else.

let valorModulo1;
let permissoes = new Array(36);
for (let i = 0; i < 36; i++) permissoes[i] = "0";

if (permissoes[0] == "0" && permissoes[5] == "0" && permissoes[10] == "0" && permissoes[15] == "0" && permissoes[20] == "0" && permissoes[25] == "0" && permissoes[30] == "0" && permissoes[35] == "0") {
    valorModulo1 = "0";
} else {
    valorModulo1 = "1";
}

console.log(valorModulo1);
permissoes[0] = "1";

if (permissoes[0] == "0" && permissoes[5] == "0" && permissoes[10] == "0" && permissoes[15] == "0" && permissoes[20] == "0" && permissoes[25] == "0" && permissoes[30] == "0" && permissoes[35] == "0") {
    valorModulo1 = "0";
} else {
    valorModulo1 = "1";
}

console.log(valorModulo1);

I put in the Github for future reference.

1

This will be interpreted as follows:

If permissions[0] is a value Truthy, or permissions[5] is a value Truthy, and so on, and not if any of these is == "0".

What you want to do is something like this:

if(permissoes[0] || permissoes[5] ... permissoes[35]) {
   valorModulo1 = "1";
} else {
   valorModulo1 = "0";

}

Browser other questions tagged

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