javascript 与或非运算符详解

突然发现逻辑与或操作对象的问题,查了一下国外的资料。下面是自己的总结:

逻辑与
注意:逻辑与操作数可以是任何类型,不仅仅是bool类型的
当其中一个操作数不是bool类型时,其返回值不一定是bool类型的

如果一个操作数是object,另外一个操作数是bool类型的,返回bool值:
例: document.body && false = false;

如果两个操作数都是object,返回第二个操作数
例: document.body && 123 = 123; 123 && document.body = object

任意一个操作数是null,返回null
任意一个操作数是NaN,返回NaN
任意一个操作数是undefined,返回undefined
例: true && null = null; true && NaN = NaN; true && undefined = undefined;

Logical AND

var bTrue = true;
var bFalse = false;
var bResult = bTrue && bFalse;

Attention:Logical AND can be used with any type of operands, not just Boolean values. When either operand is not a primitive Boolean, logical AND does not always return a Boolean value:

If one operand is an object and one is a Boolean, the object is returned.(有错误)
If both operands are objects, the second operand is returned.
If either operand is null, null is returned.
If either operand is NaN, NaN is returned.
If either operand is undefined, an error occurs.(有错误)


逻辑或
注意:类似逻辑与一样,如果两个操作数不都是bool类型的时候,返回值不一定是bool类型的

如果一个操作数是object另外一个是bool类型,返回object
例: document.body || false = object;

如果两个操作数都是object,返回第一个object
例: 123 || document.body = 123 ; document.body || 123 = object

如果两个操作数都是null,返回null,NaN 和 undefined类似
例: null || null = null; NaN || NaN = NaN; undefined || undefined = undefined;

如果两个之中有一个是null或NaN或者undefined,返回另外一个操作数
例: null || 123 = 123; NaN || 123 = 123; undefined || document.body = object;

Logical OR

var bTrue = true;
var bFalse = false;
var bResult = bTrue || bFalse;

注意:Just like logical AND, if either operand is not a Boolean, logical OR will not always return a Boolean value:

If one operand is an object and one is a Boolean, the object is returned.
If both operands are objects, the first operand is returned.
If both operands are null, null is returned.
If either operand is NaN, NaN is returned. (测试了下,返回另外一个操作数)
If either operand is undefined, an error occurs. (测试了下,返回另外一个操作数)

你可能感兴趣的:(Javascript)