var o={flag:true}; var test=!!o.flag;//等效于var test=o.flag||false; alert(test);
由于对null与undefined用!操作符时都会产生true的结果,所以用两个感叹号的作用就在于,如果明确设置了o中flag的值(非null/undefined/0""/等值),自然test就会取跟o.flag一样的值;如果没有设置,test就会默认为false,而不是null或undefined。 在jQuery中比较经典的例子如下:(jQuery 1.7.0.js: Line 748)
grep: function( elems, callback, inv ) { var ret = [], retVal; inv = !!inv;
// Go through the array, only saving the items // that pass the validator function for ( var i = 0, length = elems.length; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } }