[英]can someone please explain the syntax of the conditional operator below and what exactly it's doing
下面我提供了兩個例子(即a和b)。 查看基本形式的條件運算符(示例 b),我無法理解如何:
(root = document.documentElement) || (root = document.body.parentNode)
例如一個
導致 boolean 值導致操作員使用“root”或“document.body”。
一個。 我不明白的形式的條件運算符:
(((root= document.documentElement) || (root= document.body.parentNode)) && typeof root.scrollLeft == 'number'? root: document.body).scrollLeft
灣。 基本形式的條件運算符:
(conditional test) ? if true do this : if false do this;
有人可以告訴我示例a中到底發生了什么嗎? 謝謝。
目標是使用此代碼訪問瀏覽器 window 中對視口區域所做的滾動量,以獲取腳本,而無需訪問 window.scrollX 和 window.scrollY 屬性。
帶有邏輯運算符的表達式總是以可能的“最懶惰”的方式進行評估(從左到右)。 這意味着在“或”運算符的情況下||
,僅在找到第一個“真實”值之前對其進行評估。 評估第二項不能再改變結果。 如果是“與”運算符&&
,則評估將在第一個“假”值之后停止。 在 JavaScript 中,“真實”值被返回,而不僅僅是true
或false
。 這使得建築成為一個強大的建築。
另一點需要注意的是 JavaScript 中的“幾乎所有東西都有一個值”:即使是賦值表達式也會在賦值后返回左側變量的值。
編輯:
如果您願意,您甚至可以將上述表達式進一步精簡為:
(typeof (root = document.documentElement || document.body.parentNode)
.scrollLeft == 'number' ? root : document.body).scrollLeft
省略&&
運算符。 但這可能不是“可讀性”方面的改進。
這個東西叫做短路評估。 基本上 JS 邏輯運算符是從左到右計算的。 當您想根據OR or AND
邏輯為變量分配一些值時,此功能會派上用場。 舉些例子
true || true;
// true
true || false;
// true
false || false;
// false
在這里,如果左邊的語句為true
,那么它不會檢查右邊的條件並返回左邊的值,這稱為短路評估。
有關更多信息,請閱讀此https://codeburst.io/javascript-what-is-short-circuit-evaluation-ff22b2f5608c
以簡單直觀的方式,您可以將這兩個表達式視為以下函數:
(root = document.documentElement) || (root = document.body.parentNode)
意思是:
function test() {
root = document.documentElement
if (!root) {
root = document.body.parentNode
}
return !!root
}
test()
(((root= document.documentElement) || (root= document.body.parentNode))
&& typeof root.scrollLeft == 'number' ? root : document.body).scrollLeft
基本上意味着:
function test(){
root = document.documentElement
if (!root) {
root = document.body.parentNode
}
if (root) {
return typeof root.scrollLeft == 'number' ? root : document.body).scrollLeft
} else {
return false
}
}
test()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.