javascript - +!! if 语句中的运算符

标签 javascript

我正在审查一个 angularjs 工厂的代码,以便更好地理解它是如何工作的。该代码包含一个我不完全理解的 if 语句。

在 plnkr 演示中,作者这样写:

if ((+!!config.template) + (+!!config.templateUrl) !== 1) {
  throw new Error('Expected modal to have exactly one of either `template` or `templateUrl`');
}

It is slightly different in the github repo:

if (!(!config.template ^ !config.templateUrl)) {
  throw new Error('Expected modal to have exactly one of either `template` or `templateUrl`');
}

很明显,根据错误消息,它正在检查两者之一是否存在。我只是不确定它是如何得出结论的。我无法找到有关 ^+!

的任何信息

我的问题是:这个 if 语句是如何工作的? (特别是 ^+!+!!)

最佳答案

!! converts a value to a boolean (true or false). + 然后将该 bool 值转换为数字,1 表示 true0 表示 false。

> +true
1
> +false
0

就我个人而言,在处理两个 bool 值时,我发现这样写会更清楚:

if (!config.template == !config.templateUrl) {
  throw ...
}

显然,代码的清晰度和可读性该死。

关于javascript - +!! if 语句中的运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34501615/

相关文章:

javascript - 使用 raphael 缩放多条路径

javascript - 操纵 H1 标签

javascript - Node 遗留 url.parse 已弃用,用什么代替?

javascript - 为什么在 Javascript 中 (1,2) 等于 2?

javascript - Babel 取消了 ember.js 应用程序中大文件的样式优化

javascript - z-index 为 100 的新区 block 变得太大

javascript - 延迟 React onMouseOver 事件

javascript - HTML overflow-x 设置焦点

javascript - jQuery 使用 icheck 插件在多个复选框中显示隐藏 div

javascript onmouseout 清除html元素