javascript - javascript代码解读——三元IF运算符前的Tilde符号

标签 javascript node.js express

我在检查 express 中的 respons.js 代码时发现了这段代码:

res.contentType =
res.type = function(type){
  return this.set('Content-Type', ~type.indexOf('/')
    ? type
    : mime.lookup(type));
};

我的问题是 ~ 运算符在 type.indexOf() 语句前面做了什么?它的用途是什么,何时使用?

最佳答案

这是一个bitwise NOT , 虽然它在这里的使用是相当不透明的。

它用于将 indexOf-1 结果(即未找到字符串)转换为 0,这是一个虚假值(因为 ~-1 == 0,并且 0 在 bool 上下文中为假),它让所有其他值保持真实。

可以更清楚地写成 (type.indexOf('/') != -1) ? ... : ...

用简单的英语来说,它说,“将来自 indexOf-1 结果(即,如果未找到 /)视为 false;否则,将结果视为true”。

关于javascript - javascript代码解读——三元IF运算符前的Tilde符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16845228/

相关文章:

javascript - 如何在正则表达式中使用变量?

javascript - JIRA 有调用 JQuery(window).ready 的方法吗?

javascript - 在特定像素处减慢/停止/暂停滚动

node.js - 使用 pem 证书向远程代理发送消息

node.js - 未处理的 promise 拒绝 AOT(提前)Angular 2

node.js - express/connect 中间件的控制顺序

javascript - 带 noop 的 Node 控制台包装器

javascript - 关于 map 物种文件(和目的)的困惑

node.js - Node + Express + Passport : req. 用户未定义

node.js - Express.js 4 和域模块 : why domain doesn't handle the error?