Javascript chrome 的 V8 中的 && 运算符行为
Javascript && operator behavior in chrome's V8
因为我正在编写 javascript 解释器,所以我需要实现一些基本功能。我在我的 Chrome 控制台上玩了一会儿,我在 js 中发现了这种奇怪的行为。我如何解释 js 在这种特殊情况下的作用?
谢谢
Javascript的&&
运算符returns左边部分如果可以转换为false
,否则returns右边部分
所以在这两种情况下,您都会得到右边的表达式(因为 012
和 true
都不能转换为 false
)。对于第一种情况,true
,对于第二种情况,012
.
由于 012
是八进制,您将得到 10
输出,这是八进制 12
的 base-10 表示
我找不到更好的 link 作为来源,所以我将引用这个(它不是 V8 特定的,但应该这样做):https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators
Logical AND (&&)
expr1 && expr2
Returns expr1
if it can be converted to false; otherwise, returns expr2
. Thus, when used with Boolean values, && returns true if both operands can be converted to true; otherwise, returns false.
(粗体是我的)
我解释 &&
和 ||
运算符的方式是这样的:
a && b = a ? b : a;
a || b = a ? a : b;
因为我正在编写 javascript 解释器,所以我需要实现一些基本功能。我在我的 Chrome 控制台上玩了一会儿,我在 js 中发现了这种奇怪的行为。我如何解释 js 在这种特殊情况下的作用?
谢谢
Javascript的&&
运算符returns左边部分如果可以转换为false
,否则returns右边部分
所以在这两种情况下,您都会得到右边的表达式(因为 012
和 true
都不能转换为 false
)。对于第一种情况,true
,对于第二种情况,012
.
由于 012
是八进制,您将得到 10
输出,这是八进制 12
我找不到更好的 link 作为来源,所以我将引用这个(它不是 V8 特定的,但应该这样做):https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators
Logical AND (&&)
expr1 && expr2
Returns
expr1
if it can be converted to false; otherwise, returnsexpr2
. Thus, when used with Boolean values, && returns true if both operands can be converted to true; otherwise, returns false.
(粗体是我的)
我解释 &&
和 ||
运算符的方式是这样的:
a && b = a ? b : a;
a || b = a ? a : b;