menu

开发进行时...

crazy coder

Avatar

你真的理解了JavaScript的逻辑操作符吗?

在javascript中使用&&、||、!来实现逻辑运算,其基本用法相信大家已经熟知,本文将深入介绍其工作机制,相信对大家更加灵活的使用javascript会用帮助。

每个逻辑表达式都是有返回值的,但这个值并不一定是布尔变量,下面分别介绍:
(1)与操作符(&&)
与操作符的执行过程如下:JavaScript依次获取每一个操作数,将它们转换为布尔变量,如果是false,则直接返回这个操作数的值(注意,返回的是转换前的原值,不一定是布尔类型),中断后面操作数的处理;否则继续处理下一个操作数。如果直到最后一个操作数仍然对应布尔变量true,则返回最后这个操作数的值,下面的代码演示了其执行原理:
var a="1" && true && 0 && false && "abc";
alert(a); //可见a的值是0
var b="abc" && true && "123";
alert(b); //可见b的值是"123";

(2)或操作符(||)
和与操作符类似,或操作符的执行过程如下:JavaScript依次获取每一个操作数,将它们转换为布尔变量,如果是true,则直接返回这个操作数的值,中断后面操作数的处理;否则继续下一个操作数。如果知道最后一个操作数仍然对应布尔变量false,则返回这个操作数的值。下面的代码演示了其执行原理:
var a="abc" || "123";
alert(a); //可见a的值是"abc"
var b=false || "" || 0;
alert(b); //可见a的值是0

或操作符的这一性质在开发中经常会用到。
(3)非操作符(!)
和前两种操作符不同,非操作符始终返回布尔类型的变量,例如:
var a=! "abc";
alert(a); //显示a的值为false


from x2blog

side-effect


“犀牛书”5.7 Logical Operators一章有提及:

When used with boolean operands, the && operator performs the Boolean AND operation on the two values: it returns true if and only if both its first operand and its second operand are true. If one or both of these operands is false, it returns false.

The actual behavior of this operator is somewhat more complicated. It starts by evaluating its first operand, the expression on its left. If the value of this expression can be converted to false (for example, if the left operand evaluates to null, 0, "", or undefined), the operator returns the value of the lefthand expression. Otherwise, it evaluates its second operand, the expression on its right, and returns the value of that expression.

评论已关闭