JavaScript中的运算符顺序(||,&&) [英] The order of operators in JavaScript (|| ,&&)
问题描述
我正在阅读Underscore.js的源代码,然后让我感到困惑:
I am reading the source code of Underscore.js, then something confused me:
// Its code, check the passed-in parameter obj
_.isObject = function(obj) {
var type = typeof obj;
return type === 'function' || type === 'object' && !!obj;
};
我对运算符的表达顺序感到困惑.
I am confused about the operator order of expression.
我认为运算符优先于
return type === 'function' || type === 'object' && !!obj;
将从left
到right
;我的意思是等于:
will be from left
to right
; I mean equal to :
return (type === 'function' ) || ( type === 'object' && !!obj);
如果type
等于function
则返回true
;否则操作type === 'object' && !!obj
;如果type
等于object
返回!!obj
,与Boolean(obj)
相同;否则返回false
;
if type
equal function
return true
; else operate type === 'object' && !!obj
; if type
equal object
return !!obj
,same as Boolean(obj)
; else return false
;
我举了一些例子:
var a = alert(1) || alert(2) && alert(3);
alert(a); //result : 1, 2 undefined;
var a = alert(1) || alert(2) && 0;
alert(a); //result : 1, 2 undefined;
什么让我感到困惑:
-
为什么
!!obj
应该存在?如果我们删除!!obj
,代码也会运行.
Why
!!obj
should exist? if we delete!!obj
, code run as well.
此代码的运算符顺序?我知道&&
运算符高于||
,所以我猜想obj为空时的!!obj
效果,但是当我练习那不是我想要的时;
the operator order of this code? I know &&
operator are higher than ||
, so I guess !!obj
effect when obj is null, but when I practice that is no what I want;
推荐答案
如果对象是null
,他们想返回false
.通常,当我们需要知道某物是否为对象时,null
并不是我们想要的.这是因为尝试访问null
的属性(例如,null[propName]
)会引发错误.
They want to return false
if the object is null
. Usually when we need to know if something is an object, null
is not what we're looking for. That's because trying to access null
's properties (null[propName]
for example) would throw an error.
console.log(typeof null);
表达式type === 'function' || type === 'object' && !!obj;
的执行顺序是从左到右:
The order of execution for the expression type === 'function' || type === 'object' && !!obj;
is from left to right:
-
type === 'function' - if this is
truethe expression will return
true`,而不计算其余部分 -
type === 'object'
-如果这是false
,则表达式将返回false
,不计算最后一部分 -
!!obj
-null
将返回false
,其他任何对象将返回true
type === 'function' - if this is
truethe expression will return
true` without computing the resttype === 'object'
- if this isfalse
the expression will returnfalse
without computing the last part!!obj
-null
would returnfalse
, any other object would returntrue
该片段演示了流程:
step(false, 1) || step(true, 2) && step(true, 3)
function step(ret, step) {
console.log(step);
return ret;
}
使用
!!
我们可以将值强制转换为布尔值-因此真实值应为 转换为true,例如!!{} === true
,而伪造为 错误,例如!!null === false
.
Using
!!
we can cast values to booleans - So truthy values would be converted to true, for example!!{} === true
, and falsy ones to false, for example!!null === false
.
这篇关于JavaScript中的运算符顺序(||,&&)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!