First view &&
<script language="javascript" type="text/javascript"> var a =1; var b = 0; var c = 3; var d = a && b && c; window.alert(d); </script>
The output value of D is 0. If the value of D is changed to a value not equal to 0, D will always be 3.
Therefore, in JS, "&" returns the first non-true value, that is, 0 (the object can also be). If all are true, the last value is returned.
<script language="javascript" type="text/javascript"> var a =0; var b = 3; var c = 5; var d = a || b || c; window.alert(d); </script>
The output value of D is 3. If the value of B is changed to 0, D is always 5. If all values are changed to 0, the value of D is 0.
Therefore, | in JS returns the first value not false, that is, 0 (the object can also be). If all values are false, the last value is returned.
Application:
For example, to verify the mailbox format in a simple way, the format is correct only when both '@' and '.' exist. Otherwise, an error is prompted:
Which one should I use? Let's analyze:
If (form1.elements [3]. value. indexof ("@", 0) =-1 & form1.elements [3]. value. indexof (". ", 0) =-1) {alert (" Incorrect email address! ")}
If both exist: & both sides are false. & Returns the first true value. Therefore, if the condition is false, the statement following the if statement is not executed! The user is not prompted.
Only @ and. A user error is prompted only when the if condition is true.
When both exist, the last value is returned, which is the true if judgment condition is true if statement execution. A user error is prompted.
So use & obvious error!
Replace it with if (form1.elements [3]. value. indexof ("@", 0) =-1 | form1.elements [3]. value. indexof (". ", 0) =-1) {alert (" Incorrect email address! ")}
Analysis:
If both exist: if all are false, the return value is false. Therefore, the IF condition is not true and the statement is not executed. No error is prompted!
If only one exists, the first value not false is returned. Returns true with an error message!
Both do not exist: the first value not false is returned, and the return value is true. The error message is returned!
So it should be used |