2014-08-30 424 views
-5

我是新手,並試圖學習JavaScript自己。什麼是「||」意思?

有一個例子:

var scrollTop = document.documentElement.scrollTop || document.body.scrollTop 

我只是想知道什麼是符號 「||」做?謝謝!感謝你的幫助。

+6

這是JavaScript的[邏輯OR運算符](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators),它返回第一個操作數的值,如果它是真值否則返回第二個操作數的值。 – nnnnnn 2014-08-30 07:25:31

+0

也http://stackoverflow.com/questions/2851404/what-does-options-options-mean-in-javascript,http://stackoverflow.com/questions/7718259/what-does-mean(和*許多*更多,我只是搜索''[javascript]「||」') – user2864740 2014-08-30 07:29:23

+0

乾杯傢伙,這可以幫助我很多! 「 – 2014-08-30 08:13:53

回答

6

這意味着你正在試圖獲得document.documentElement.scrollTop功能,但如果它返回undefined(因爲功能沒有在給定的瀏覽器支持),它會改用document.body.scrollTop函數。

+2

如果'document.documentElement.scrollTop' _is_被定義但恰好具有值'0',那麼該語句將採用'document.body.scrollTop'的值。 – nnnnnn 2014-08-30 07:33:49

0

如果document.documentElement.scrollTopundefinednullscrollTop=document.body.scrollTop

0

這裏||邏輯或操作。

Logical OR operator returns the first value of first operand if that is truthy 
otherwise it returns the second operand. 

上面的語句是一樣的

if(document.documentElement.scrollTop){ 
    var scrollTop = document.documentElement.scrollTop 
} 
else{ 
    var scrollTop = document.body.scrollTop 
} 
+0

_」的值爲空/未定義的_ _或零或假或空字符串或NaN。 – nnnnnn 2014-08-30 07:32:40

+0

@nnnnnn更新了我的答案。我得到了'0','''''''NaN'也是很麻煩的。 – Mritunjay 2014-08-30 07:34:47