[英]Type-checking the result of operator statements
a = 'A';
b = null;
const w = a === b;
const x = a && a.length;
const y = b && b.length;
const z = (a && a.length) || (b && b.length);
const u = (a && a.length) && (b && b.length);
console.log(typeof w); // boolean
console.log(typeof x); // number
console.log(typeof y); // object
console.log(typeof z); // number
console.log(typeof u); // object
I was expecting all of them to be boolean?我期待他们都是boolean? Can you please help me understand why some of them are not boolean ?你能帮我理解为什么其中一些不是 boolean 吗?
It is not obvious to me why short-circuit evaluation results in different z and u types.我不清楚为什么短路评估会导致不同的 z 和 u 类型。
x, y, z, u
are short circuit evaluations and not conditions. x, y, z, u
是短路评估,而不是条件。
const x = a && a.length;
What that means is assign a.length
to x
is a
exists and so on.这意味着将a.length
分配给x
is a
exists 等等。 Hence a number
.因此有一个number
。
Whereas if you were to put them inside an if condition they would be implicitly type casted to boolean
而如果您将它们放在 if 条件中,它们将被隐式类型转换为boolean
const a = null || "works." console.log(a)
If you run the above snippet you will realise how ||
如果你运行上面的代码片段,你会意识到||
works.作品。 If the value on the left of ||如果 || 左边的值evaluates to false then value on right is returned otherwise left value.计算结果为假,则返回右边的值,否则返回左边的值。
const x = a && a.length; // a.length = 1 const y = b && b.length; // b = null const z = (a && a.length) || (b && b.length); // a.length = 1 const u = (a && a.length) && (b && b.length); // b = null a && a.length // ===> true and 1 b && b.length // ===> false and next line;
x || y
x || y
if x is true return x and y not exec, if x is false return y; x || y
如果 x 为真,则返回 x 并且 y 不执行,如果 x 为假,则返回 y;
x && y
if x is true return y, if x is false return x; x && y
如果 x 为真,则返回 y,如果 x 为假,则返回 x;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.