简体   繁体   中英

IF formula with OR statement not working as expected - what am I doing wrong?

I have a script that retrieves four values. For the sake of simplicity I've replaced them with actual numbers here.

It then decides which function to proceed with based on an if statement:

function myFunction() {

    var firstvar = 1000;
    var secondvar = (100 - firstvar);
    var thirdvar = 1000;
    var fourthvar = (100 - thirdvar);

    if (secondvar < 0 || fourthvar < 0) {

        first function here

    } else {

        second function here

    }
};

I only want the first function to perform if either secondvar or fourthvar are negative numbers, else I want the second function to perform.

EDIT: The above script is now working as expected. I had been confused between using and (&&) and or (||).

function myFunction() {

  var firstvar = 1000;
  var secondvar = (100 - firstvar);
  var thirdvar = 1000;
  var fourthvar = (100 - thirdvar);

  if (secondvar < 0 && fourthvar < 0) {

    firtFunction()

  } else {

    secondFunction()

  }
};

您需要和“和”,而不是“或”:

if (secondvar < 0 && fourthvar < 0) {

What is not working? Works fine.

 function myFunction() { var firstvar = 1000; var secondvar = (100-firstvar); var thirdvar = 1000; var fourthvar = (100-thirdvar); if (secondvar < 0 || fourthvar < 0) { console.log('yep'); } else { console.log('nope'); } }; myFunction();

Your function looks right to me, maybe there is some issue in the code that we are not seeing here, please show the error or the issue you are facing when running the script

If i run the below ocde in my broswer, it alerts Yep The issue is with some other code which we are not seeing here

<script>
unction myFunction() {
var firstvar = 1000;
var secondvar = (100-firstvar);
var thirdvar = 1000;
var fourthvar = (100-thirdvar);
if (secondvar < 0 || fourthvar < 0) {
alert('yep');
 } else {
    alert('nope');
}
};
 myFunction();
 </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM