我正在審閱angularjs工廠的代碼以更好地理解它的工作原理。該代碼包含我不完全瞭解的if
聲明。+ !! 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`');
}
顯然通過它檢查是否存在兩個中的一個錯誤消息。我不確定它是如何得出結論的。我一直未能找到任何信息^
或+!
我的問題是:這是如何聲明工作? (^
或+!
或+!!
特異性)
^是JavaScript的按位XOR運算符。 – Jacques
'我沒有找到任何關於^或+!的信息''您沒有使用正確的關鍵字。搜索'javascript operator' –
首先!採用類似於config.template的值(這可能是因爲+ !!而產生的一個數字),根據它是零(假)還是非零(真)將其轉換爲真或假 - 這反轉了邏輯意義 - 然後第二個!將其反轉回相同的邏輯意義而不是反轉,那麼+將真/假當作數字1或0.所以,如果它沒有設置,+ !!將導致* number * 0,否則它將是* number * 1 *,無論.template的實際數值是多少*。然後他們可以做兩個表達式之間的+。 – simpleuser