var a=true;
console.log(a);//返回true
console.log(typeof a);//返回boolean
console.log(typeof(typeof a));//返回"string"
Essentially typeof a ? 1 : 2 can be written like this:
"boolean" ? 1:2
And this ternary expression calls Boolean() to convert the string type, that is: Boolean("boolean") ====>true So the return is 1. You can try assigning a to false, and the return value will still be 1:
Taking your example, the ternary operator, when typeof a is true, returns 1, and when typeof a is false, it returns 2. The first 100 + a; has been type converted, so 100 + a = 101, so results also returns 1
1. Because
typeof
has a higher priority2. Or because the addition operator has a higher priority
Essentially typeof a ? 1 : 2 can be written like this:
And this ternary expression calls Boolean() to convert the string type, that is:
Boolean("boolean") ====>true
So the return is 1.
You can try assigning a to false, and the return value will still be 1:
This statement is compiled like this
(typeof a)? 1 : 2
When it was compiled, it was changed to this form, and this is the result. Ternary operator
Nothing wrong
Taking your example, the
ternary operator, when typeof a is true, returns 1, and when
typeof a is false, it returns 2.
The first 100 + a; has been type converted, so 100 + a = 101,
so results also returns 1