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. (测试了下,返回另外一个操作数)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值