JavaScript中的运算符顺序(||,&&) [英] The order of operators in JavaScript (|| ,&&)

查看:76
本文介绍了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;

将从leftright;我的意思是等于:

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;

什么让我感到困惑:

  1. 为什么!!obj应该存在?如果我们删除!!obj,代码也会运行.

  1. 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:

  1. type === 'function' - if this is true the expression will return true`,而不计算其余部分
  2. type === 'object'-如果这是false,则表达式将返回 false,不计算最后一部分
  3. !!obj-null将返回false,其他任何对象将返回true
  1. type === 'function' - if this istruethe expression will return true` without computing the rest
  2. type === 'object' - if this is false the expression will return false without computing the last part
  3. !!obj - null would return false, any other object would return true

该片段演示了流程:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆