In a test set compiled by cssrain, there is such a question:
<Script language = "JavaScript">
Var a = 0;
Var B =-1;
Var c = 1;
Function assert (aVar ){
If (aVar = true) alert (true );
Else alert (false );
}
Assert ();
Assert (B );
Assert (c );
</SCRIPT>
Run code box
<Script language = "JavaScript"> var a = 0; var B =-1; var c = 1; function assert (aVar) {if (aVar = true) alert (true); else alert (false);} assert (a); assert (B); assert (c ); </SCRIPT> <br/> <center> If the page cannot be displayed, press Ctrl + F5 to refresh the page. For more webpage code: <a href = 'HTTP: // www.bkjia.com/'target = '_ blank'> http://www.bkjia.com/</a> </center>
Tip: the code can be modified before running!
In my understanding, the Boolean value of any non-0 value should be true.
However, the correct output of this question is: false true.
The value of (-1 = true) is false.
Let's take a look at the following example:
<Script language = "JavaScript">
Var a = 0;
Var B =-1;
Var c = 1;
Function assert (aVar ){
If (aVar) alert (true );
Else alert (false );
}
Assert ();
Assert (B );
Assert (c );
</SCRIPT>
<Script language = "JavaScript"> var a = 0; var B =-1; var c = 1; function assert (aVar) {if (aVar) alert (true ); else alert (false);} assert (a); assert (B); assert (c); </SCRIPT> <br/> <center> If the effect cannot be displayed, press Ctrl + F5 to refresh the page. For more webpage code: <a href = 'HTTP: // www.bkjia.com/'target = '_ blank'> http://www.bkjia.com/</a> </center>
Tip: the code can be modified before running!
The running results are as follows: false, true, and true.
Here, we find that the results of if (aVar) And if (aVar = true) are different.
The explanation of cssrain in the answer is:
If (aVar) And if (aVar = true) have different answers to negative numbers.
Is it because of a negative number? Let's look at the example below:
Run code box
<Script language = "JavaScript"> alert (2 = true); </SCRIPT> <br/> <center> If the effect cannot be displayed, press Ctrl + F5 to refresh the page, more webpage code: <a href = 'HTTP: // www.bkjia.com/'target = '_ blank'> http://www.bkjia.com/</a> </center>
Tip: the code can be modified before running!
Why does positive number 2 Return false. Convert the number to a boolean value.
Run code box
<Script language = "JavaScript"> alert (the Boolean Value of "2 is" + Boolean (2); alert ("the Boolean value of 0 is" + Boolean (0 )); alert ("-1 Boolean value is" + Boolean (-1); </SCRIPT> <br/> <center> If the effect cannot be displayed, press Ctrl + F5 to refresh the page. For more webpage code: <a href = 'HTTP: // www.bkjia.com/'target = '_ blank'> http://www.bkjia.com/</a> </center>
Tip: the code can be modified before running!
- 2 pages in total:
- Previous Page
- 1
- 2
- Next Page