Home > Web Front-end > JS Tutorial > Discuss the double exclamation mark judgment in js_javascript skills

Discuss the double exclamation mark judgment in js_javascript skills

WBOY
Release: 2016-05-16 17:16:30
Original
1522 people have browsed it

Looking at the qunit source code today, I found a very strange piece of code. Although I can understand its meaning, I don't understand the role of the double exclamation mark.

Copy code The code is as follows:

function id( name ) {
return !! ( typeof document !== "undefined" && document && document.getElementById ) &&
           document.getElementById( name );
}

Then I checked some information online, he was quite For the ternary operator, returns a boolean value.
Copy code The code is as follows:

var ret = !!document.getElementById

is equivalent to:
Copy code The code is as follows:

var ret = document.getElementById ? true : false;   

Returns true when the value is a non-empty string and a non-zero number, returns false when the value is an empty string, 0 or null.
Copy code The code is as follows:

var a = " "; alert(!!a) ; //true
var a = "s"; alert(!!a); //true
var a = true; alert(!!a); //true
var a = 1; alert(!!a); //true
var a = -1; alert(!!a); //true
var a = -2; alert(!!a); //true

var a = 0; alert(!!a); //false
var a = ""; alert(!!a); //false
var a = false; alert(!! a); //false
var a = null; alert(!!a); //false
Related labels:
js
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template