美文网首页
CocosCreator-如何判断undefined和null

CocosCreator-如何判断undefined和null

作者: 程序猿TODO | 来源:发表于2021-03-31 09:24 被阅读0次

    不当用法

    有时为了判断某个值有效,JS新手会写这种臃肿代码:

    if (data != null && typeof(data) != undefined && data != '') {
        ...
    }
    

    为避免这种情况,首先要了解undefinednull的区别。

    什么是undefined和null

    当声明的变量未被初始化时,默认值为undefined。如:

    let myVal; // undefined
    

    null表示尚未存在的对象。如:

    let testNode = this.node.getChildByName('noExist'); // 没有noExist节点,testNode为null
    

    如何判断undefined和null

    测试证明对undefinednull空字符串取反为true,对其余任何值取反都为false。如:

    !undefined; // true
    !null; // true
    !''; // true
    !1; // false
    !'123'; // false
    

    所以,如果想判断一个值是undefinednull空字符串中的一种,只要用 ! 就可以。如:

    if (!data) {
        ...
    }
    

    同理,如果想判断一个值不是undefinednull空字符串中的一种,则用 !! 就可以。如:

    if (!!data) {
        ...
    }
    

    相关文章

      网友评论

          本文标题:CocosCreator-如何判断undefined和null

          本文链接:https://www.haomeiwen.com/subject/kgqrhltx.html