zoukankan      html  css  js  c++  java
  • javascript中的2个感叹号的用法

    !!是逻辑"非非",即是在逻辑“非”的基础上再"非"一次。通过!或!!可以将很多类型转换成bool类型,再做其它判断。

     

      应用场景:判断一个对象是否存在

    假设有这样一个json对象:{ color: "#E3E3E3", "font-weight": "bold" },需要判断是否存在,用!!再好不过。

     

    如果仅仅打印对象,无法判断是否存在:

    var temp = { color: "#A60000", "font-weight": "bold" };
    alert(temp);
    结果:[object: Object]

     

    如果对json对象实施!或!!,就可以判断该json对象是否存在:

    var temp = { color: "#A60000", "font-weight": "bold" };
    alert(!temp);
    结果:false

     

    var temp = { color: "#A60000", "font-weight": "bold" };
    alert(!!temp);
    结果:true

     

      通过!或!!把各种类型转换成bool类型的惯例

    □ 对null的"非"返回true

    var temp = null;
    alert(temp); 
    结果:null

     

    var temp = null;
    alert(!temp); 

    结果:true

     

    var temp = null;
    alert(!!temp); 
    结果:false

     

    □ 对undefined的"非"返回true

    var temp;
    alert(temp);
    结果:undefined

     

    var temp;
    alert(!temp);

    结果:true

     

    var temp;
    alert(!!temp);

    结果:false

     

    □ 对空字符串的"非"返回true

    var temp="";
    alert(temp);
    结果:空

     

    var temp="";
    alert(!temp);
    结果:true

     

    var temp="";
    alert(!!temp);

    结果:false


    □ 对非零整型的"非"返回false

    var temp=1;
    alert(temp);
    结果:1

     

    var temp=1;
    alert(!temp);
    结果:false

     

    var temp=1;
    alert(!!temp);

    结果:true

     

    □ 对0的"非"返回true

    结果:0

    var temp = 0;
    alert(temp);

     

    var temp = 0;
    alert(!temp);
    结果:true

     

    var temp = 0;
    alert(!!temp);
    结果:false

     

    □ 对字符串的"非"返回false

    var temp="ab";
    alert(temp);
    结果:ab

     

    var temp="ab";
    alert(!temp);
    结果:false

     

    var temp="ab";
    alert(!!temp);
    结果:true

     

    □ 对数组的"非"返回false

    var temp=[1,2];
    alert(temp);

    结果:1,2

     

    var temp=[1,2];
    alert(!temp);
    结果:false

     

    var temp=[1,2];
    alert(!!temp);
    结果:true
  • 相关阅读:
    GIL全局解释器锁、死锁、递归锁以及event事件与信号量、线程queue
    进程通信、消费者模型和线程
    COM inerop 创建自定义互操作集 问题
    工业自动化软件产业发展的探索与实践
    为什么都是a
    Dictionary用“集合初始值设定项”进行初始化
    非“自动实现的属性”也可以用“对象初始值设定项”进行初始化
    通过接口来解开依赖
    什么叫委派
    私有可写属性
  • 原文地址:https://www.cnblogs.com/darrenji/p/3666667.html
Copyright © 2011-2022 走看看