Qu'est-ce que c'est ! ! (non pas) opérateur en JavaScript

Mots clés : javascriptoperatorsjavascript

meilleur 4 Réponses Qu'est-ce que c'est ! ! (non pas) opérateur en JavaScript

vote vote

94

!oObject  // inverted boolean !!oObject // non inverted boolean so true boolean representation 
const isIE8 = !! navigator.userAgent.match(/MSIE 8.0/);   console.log(isIE8); // returns true or false  
console.log(navigator.userAgent.match(/MSIE 8.0/));   // returns either an Array or null   
console.log(!!navigator.userAgent.match(/MSIE 8.0/));   // returns either true or false 
vote vote

86

// Maximum Obscurity: val.enabled = !!userId;  // Partial Obscurity: val.enabled = (userId != 0) ? true : false;  // And finally, much easier to understand: val.enabled = (userId != 0); 
vote vote

72

          !!false === false            !!true === true                !!0 === false !!parseInt("foo") === false // NaN is falsy               !!1 === true              !!-1 === true  // -1 is truthy           !!(1/0) === true  // Infinity is truthy               !!"" === false // empty string is falsy           !!"foo" === true  // non-empty string is truthy         !!"false" === true  // ...even if it contains a falsy value       !!window.foo === false // undefined value is falsy       !!undefined === false // undefined primitive is falsy            !!null === false // null is falsy               !!{} === true  // an (empty) object is truthy              !![] === true  // an (empty) array is truthy; PHP programmers beware! 
vote vote

62

// this won't tell us anything about HTML5 `<audio>` as a feature var foo = function(tag, atr) { return document.createElement(tag)[atr]; }  // this won't return true if the feature is detected (although it works just fine) var bar = function(tag, atr) { return !document.createElement(tag)[atr]; }  // this is the concise, feature-detecting solution we want var baz = function(tag, atr) { return !!document.createElement(tag)[atr]; }  foo('audio', 'preload'); // returns "auto" bar('audio', 'preload'); // returns false baz('audio', 'preload'); // returns true 
// the native `hasOwnProperty` method var qux = function(tag, atr) { return document.createElement(tag).hasOwnProperty(atr); }  // the `in` operator var quux = function(tag, atr) { return atr in document.createElement(tag); }  qux('audio', 'preload');  // returns true quux('audio', 'preload'); // returns true 

Questions similaires