+ !!if语句中的运算符 [英] +!! operator in an if statement

查看:74
本文介绍了+ !!if语句中的运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查看angularjs工厂的代码,以更好地了解其工作方式.该代码包含一个我不完全理解的 if 语句.

I was reviewing the code for an angularjs factory to better understand how it works. The code contains an if statement that I don't fully understand.

在plnkr演示中,作者写道:

In a plnkr demo the author wrote this:

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

在github存储库中略有不同:

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

显然,通过错误消息,它正在检查是否存在两者之一.我只是不确定如何得出结论.我无法找到有关 ^ +!

Obviously by the error message it is checking to see if one of the two exists. I'm just not sure how it comes to the conclusion. I have not been able to find any information on ^ or +!

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

My question is: How does this if statement work? (^ or +! or +!! specifically)

推荐答案

!! converts a value to a boolean (true or false). + then converts that boolean to a number, either 1 for true or 0 for false.

> +true
1
> +false
0

我个人认为,在处理两个布尔值时,写这样的东西会更清楚:

Personally I find it clearer to write something like this, when dealing with two booleans:

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

显然,代码的清晰度和可读性受到了谴责.

Code clarity and readability be damned, apparently.

这篇关于+ !!if语句中的运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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