zoukankan      html  css  js  c++  java
  • JavaScript中两个感叹号的作用

    先用一个简单的例子说明:
    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 ] );
                }
            }

            return ret;
        }
    在使用grep函数的时候,如果给出了第三个参数且非null/undefined/0""/等值,则inv为true,否则为false。这样做的目的就是保证inv和retVal的值都只能在true/false中取,而非其它值,为后续判断提供便利。

    如果感觉不错,请 一个!
    by simpman
  • 相关阅读:
    P3952 [NOIP2017 提高组] 时间复杂度
    1905. 统计子岛屿
    1102 Invert a Binary Tree (25 分)
    P1077 [NOIP2012 普及组] 摆花
    P3915 树的分解
    P1045 [NOIP2003 普及组] 麦森数
    P4961 小埋与扫雷
    P1123 取数游戏
    P1460 [USACO2.1]健康的荷斯坦奶牛 Healthy Holsteins
    CF1059B Forgery
  • 原文地址:https://www.cnblogs.com/simpman/p/2947806.html
Copyright © 2011-2022 走看看