double exclamation on a return value in javascript
This question already has an answer here:
The !
operator negates, and the secondary !
negates the result of the inital negation. This basically typecasts whatever is on the right hand side into a boolean ( true or false ).
!false // true
!!false // false
So if the method is defined then the function
which is truthy, will be typecasted into true
.
document.createElement('video').canPlayType
So the above returns a function. We don't want a function, we want an explicit boolean, so we negative it twice and since function
is not falsy ( 0, null, false, empty string, NaN ) then it returns true for browsers which support this method.
!!document.createElement('video').canPlayType // true
If the method is not supported, the browser will return undefined
. !undefined
is true, and !true
is false, so !!document.createElement('video').LOL
will return false
The double exclamation is a JavaScript trick to return true/false regardless of input. In your example, if a browser does not support the video tag, it will return undefined. !undefined is true. So !!undefined is false. If the browser does support video, it will return true. !!true is also true. This saves you from having to handle the case of undefined.
链接地址: http://www.djcxy.com/p/12648.html