为什么逻辑运算符(&&和||)总是返回布尔结果? [英] Why don't logical operators (&& and ||) always return a boolean result?
本文介绍了为什么逻辑运算符(&&和||)总是返回布尔结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么这些逻辑运算符返回一个对象而不是布尔值?
Why do these logical operators return an object and not a boolean?
var _ = (obj.fn && obj.fn() ) || obj._ || ( obj._ = {} );
var _ = obj && obj._;
我想了解为什么它会返回 obj.fn()<的结果/ code>(如果已定义)或
obj ._
但不是布尔结果。
I want to understand why it returns result of obj.fn()
(if it is defined) OR obj._
but not boolean result.
推荐答案
var _ = ((obj.fn && obj.fn() ) || obj._ || ( obj._ == {/* something */}))? true: false
将返回布尔值。
更新
请注意,这是基于我的测试。我不能完全依赖。
Note that this is based on my testing. I am not to be fully relied upon.
这是一个表达式不分配 true
或 false
值。而是指定计算值。
It is an expression that does not assign true
or false
value. Rather it assigns the calculated value.
让我们来看看这个表达式。
Let's have a look at this expression.
示例表达式:
var a = 1 || 2;
// a = 1
// it's because a will take the value (which is not null) from left
var a = 0 || 2;
// so for this a=2; //its because the closest is 2 (which is not null)
var a = 0 || 2 || 1; //here also a = 2;
您的表达式:
var _ = (obj.fn && obj.fn() ) || obj._ || ( obj._ = {} );
// _ = closest of the expression which is not null
// in your case it must be (obj.fn && obj.fn())
// so you are gettig this
另一个表达式:
var a = 1 && 2;
// a = 2
var a = 1 && 2 && 3;
// a = 3 //for && operator it will take the fartest value
// as long as every expression is true
var a = 0 && 2 && 3;
// a = 0
另一个表达式:
var _ = obj && obj._;
// _ = obj._
这篇关于为什么逻辑运算符(&&和||)总是返回布尔结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文