您的位置:首页 > Web前端 > JavaScript

javascript 中的 || 和 && 操作符

2012-03-09 14:29 375 查看
首先上ECMA-262 5th中的说明:

The production LogicalANDExpression : LogicalANDExpression && BitwiseORExpression is evaluated as follows:

1. Let lref be the result of evaluating LogicalANDExpression.

2. Let lval be GetValue(lref).

3. If ToBoolean(lval) is false, return lval.

4. Let rref be the result of evaluating BitwiseORExpression.

5. Return GetValue(rref).

&& 操作符是按照以下步骤计算的:

1 左边计算出结果

2 如果左边进行布尔转换为false, 则直接返回左边的表达式的结果 否则 返回右边表达式的结果

1 && 2 && 3 && 4 // 4

0 && false && undefined && null // 0


简单的理解是:左侧结果为true, 向右移动, 直至结束或遇到false.

The production LogicalORExpression : LogicalORExpression || LogicalANDExpression is evaluated as follows:

1. Let lref be the result of evaluating LogicalORExpression.

2. Let lval be GetValue(lref).

3. If ToBoolean(lval) is true, return lval.

4. Let rref be the result of evaluating LogicalANDExpression.

5. Return GetValue(rref).

|| 操作符是按照以下步骤计算的:

1 计算左边表达式的结果.

2 如果左边表达式进行布尔转换为true, 则返回左边表达式的结果 否则 返回右边表达式的结果.

1 || 2 || 3 || 4 // 1

0 || false || undefined || null // null


可以这么理解:左侧结果为false, 向右移动, 直至遇到true或者结束.

注意:返回值并非一定是布尔值, 这里和 PHP 的 || 和 && 的运算结果是不一样的(PHP永远返回布尔型的值), 他会返回左侧的表达式的值或者计算结果.

function fn1(){};

function fn2(arg){alert(arg);};

var arr1 = [];

var arr2 = [1,2];

fn1 || 1; // function fn1(){}

arr1 || 1; // []

fn2 || 0; // function fn2(arg){alert(arg);}

arr2 || 0; // [1,2]

arr2[0]+1 && 1 // 1

arr2[0]+1 || 1 // 2

true || 1; // true
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: