It is believed that every person with JS will often encounter the scenario of simplifying code with logical operators:
evnt=evnt | | window.event, ..... var obj = unknownobj1&&unknownobj2&&unknownobj3;
What are the principles of these logical operators? I tested it and made a summary.
First of all, we need to introduce the type conversion mechanism of JS. Other data types The results of ToBoolean are first put here:
- udefined, null result is false.
- Number if the argument is +0,-0, or NaN, the result is false; otherwise, true.
- String if the argument is an empty string, the result is false, otherwise true.
- Object results are true, note that empty object is also true.
Then, looking back at what the logical operators are, it's certainly not strange, because there are other languages, with &&, or | |, not!.
First Say NO! operator, false-True, true-false, the final result is a Boolean value, which is true|false.
Again, the remaining two, their return value is not necessarily true|false, there is an object when the return result is a variety of, online summary of the rules are not too good to remember. In fact, from the root of the problem to explore JS or a lot of cards, the real reason for confusion is && and | | The return value does not do a Boolean conversion, JS type conversion is done automatically when the Operation , so this practice is very reasonable and provides a lot of flexibility.
Take && For example, how do you implement the last return value representing the value of the entire expression? That is, " returns the first false value encountered, if it is true, returns the last value ." Try it, isn't it?
Console.log ("SSS" &&false//false console.log ("" &&true); // "" Console.log ("1" &&5); // 5
Because all objects are true, it is the same with object.
Console.log (obj&&false//false Console.log (1&&obj); // obj Console.log (OBJ&&OBJ2); // obj2
Therefore, it is possible to use && to make the judging element not empty and then take the value (the beginning example).
|| Similarly, returns the first true value encountered, and if all is false, returns the last one . It's not an example.
A probe into the Boolean logic operation of JavaScript