More recent interviews, but every time I asked this question, the answer came out of the students are not many
The code is as follows |
Copy Code |
var a = 0;
if (a) {
alert (1);
} |
Some people will answer alert (1) and some will not do so.
The result is not carried out, but should not carry out the students can not say why, he will only say with his experience, so here I think it is necessary to make up the basic knowledge of JS, JS basic Good People may skip this blog.
First of all, let us recall the Boolean ();
Boolean is a transformation function. That is, you can pass any value to a Boolean type, which returns True and false.
So when is true and when is false, it has a certain rule.
I use a table to show this rule.
Data type |
Value converted to True |
The value converted to false |
Boolean |
True |
False |
String |
Any non-empty string |
“” |
Number |
Any value other than 0 |
0 and Nan |
Object |
Any object |
Null |
Undefined |
|
Undefined |
Note: Undefined does not have a value converted to true.
From here we are at a glance, Boolean (0) returns false;
So when there is no expression inside an if statement, just a value such as if (XXX) it automatically performs a Boolean (XXX) operation, that is, if (XXX) = if (Boolean (XXX))
So we correspond to the above Boolean conversion rules, combined with the above questions, it is very easy to understand.
This is why if (0) returns false.