Prepare two objects for the following discussion.
1 varAlice = {2Name: "Alice",3Tostring:function () {4 return This. Name;5 }6 };7 varSmith = {8Name: "Smith",9Tostring:function () {Ten return This. Name; One } A}
In JavaScript, && is not just for a Boolean type, but for the result of a Boolean type.
L returns false directly if the first operand is of type Boolean and the value is false.
If the first operand is of type Boolean, and the value is true, and the other operand is of type object, the object is returned.
L If two operands are of type object, then the second object is returned.
L If any one of the operands is NULL, then NULL is returned.
L If any one of the operands is Nan, then the Nan is returned.
L If any one operand is undefinded, then return undefined.
1Alertfalse&& Alice);//false2Alerttrue&& Alice);//Alice3 4Alert (Alice && Smith);//Smith5Alert (Smith && Alice);//Alice6 7AlertNULL&& Alice);//NULL8Alert (NaN && Alice);//NaN9Alert (undefined && Alice);//undefinedTenAlert (Alice && undefined);//undefined
for | | , it is not just for the Boolean type, but also for returning the result of the Boolean type.
In fact, null, undefined, and NaN will all be treated as false. And the object is treated as true.
L Returns True if the first operand is of type Boolean and the value is true.
If the first operand is of type Boolean and the value is false and the second operand is object, the object is returned.
L returns the first object if all two operands are of type object.
L If two operands are null, then NULL is returned.
L If the two operands are Nan, then the Nan is returned.
L If two operands are undefined, then return to undefined.
1Alertfalse|| Alice);//Alice2 3Alerttrue|| Alice);//true4 5Alert (Alice | | smith);//Alice6 7Alert (Smith | | alice);//Smith8 9AlertNULL|| Alice);//AliceTen OneAlert (Alice | |NULL);//Alice A -AlertNULL||NULL);//NULL - theAlert (NaN | | alice);//Alice - -Alert (Alice | | NaN);//Alice - +Alert (NaN | | NaN);//NaN - +Alert (undefined | | alice);//Alice A atAlert (Alice | | undefined);//Alice - -Alert (undefined | | undefined);//undefined
You don't have to be so complicated. Recommend this part of the explanation
A && B: Converts A, B to Boolean, then logical with, True returns B, False returns a
A | | B: Converts A, B to Boolean, then logical OR, True returns a, FALSE returns B
Conversion rules:
Object is True
Non 0 digit is true
Non-empty string is true
Others are false
&& in Javascript | | Use summary