分配中的Javascript AND运算符 [英] Javascript AND operator within assignment

查看:185
本文介绍了分配中的Javascript AND运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在JavaScript中你可以这样做:

I know that in JavaScript you can do:

var oneOrTheOther = someOtherVar || "these are not the droids you are looking for...";

其中变量 oneOrTheOther 将采用第一个表达式的值,如果它不是 null undefined ,或 false 。在这种情况下,它被分配给第二个语句的值。

where the variable oneOrTheOther will take on the value of the first expression if it is not null, undefined, or false. In which case it gets assigned to the value of the second statement.

然而,当我们使用逻辑AND运算符时,变量 oneOrTheOther 会被分配给什么?

However, what does the variable oneOrTheOther get assigned to when we use the logical AND operator?

var oneOrTheOther = someOtherVar && "some string";

someOtherVar 为非时,会发生什么? false?

someOtherVar 为假时会发生什么?

What would happen when someOtherVar is non-false?
What would happen when someOtherVar is false?

刚学习JavaScript和我我很好奇与AND运算符一起分配会发生什么。

Just learning JavaScript and I'm curious as to what would happen with assignment in conjunction with the AND operator.

推荐答案

基本上,逻辑AND运算符(<如果第一个操作数是 truthy ,则code>&& )将返回第二个操作数的值,并且如果第一个操作数是 truthy ,它将返回第一个操作数的值它本身就是 falsy ,例如:

Basically, the Logical AND operator (&&), will return the value of the second operand if the first is truthy, and it will return the value of the first operand if it is by itself falsy, for example:

true && "foo"; // "foo"
NaN && "anything"; // NaN
0 && "anything";   // 0

请注意, falsy 值是强制为<$的值c $ c> false 在布尔上下文中使用时,它们是 null undefined 0 NaN ,空字符串,当然还有 false ,其他任何东西强迫 true

Note that falsy values are those that coerce to false when used in boolean context, they are null, undefined, 0, NaN, an empty string, and of course false, anything else coerces to true.

这篇关于分配中的Javascript AND运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆