我正在审查一个 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
表示 true
或 0
表示 false。
> +true
1
> +false
0
就我个人而言,在处理两个 bool 值时,我发现这样写会更清楚:
if (!config.template == !config.templateUrl) {
throw ...
}
显然,代码的清晰度和可读性该死。
关于javascript - +!! if 语句中的运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34501615/