zoukankan      html  css  js  c++  java
  • javascript判断一个变量或对象是否存在

    判断一个变量或对象是否存在,是一种常用的操作。我这里收集了几种。

    //1. 最常用的一种方法。
    if
    (typeof v == 'undefined'){ console.log("v is undefined!"); //v is undefined!
    }

      if (myObj === undefined) {

        var myObj = { };

     }

    
    

      if (myObj == null) {

        var myObj = { };

      }



    //2. 检测对象的属性是否存在不必用typeof
    var obj = {};
    if(!obj.b){
        console.log("not have attribute 'b'");   //not have attribute 'b'
    }
    
    if(window.addEventListener){ console.log("This in not IE!"); // This in not IE!
    }

    //3.在给对象添加属性时,也会遇到问题。 obj.property.number = 2; //TypeError: obj.property is undefined
     /**
        *    下面这种情况虽然没有出现语法错误,但实际上已经出现了错误.
        *    属性是复合型变量所特有的,而obj.property是数值型变量,不能含有属性.
        */
        
    var obj = {}; 
        obj.property 
    = 2 ; 
        obj.property.number 
    = 3;

    //4.直接用未定义的对象来判断,会出错。如下例。 if(!myObj1){ myObj1 = {}; //ReferenceError: myObj is not defined }
    //5. 需要如下初始化,重点在“var”。 if (!myObj2) { console.log("aaa"); //aaa      var myObj2 = { };   }
    if(!window.myObj3){ console.log("3"); //3 }

    if(!this.myObj4){ this.myObj4 = {}; console.log(4); //4}
    //或者可以这样 var global = this; if(!global.myObj5){ global.myObj5 = {}; console.log(5); } //8.由于在已定义、但未赋值的情况下,myObj的值直接等于undefined,所以上面的写法可以简化 var myObj6 ; if (myObj6 == undefined) {     var myObj6 = { }; console.log("6");   }
    //9.使用in运算符
    if(!('myObj7' in window)){ console.log("7"); }
    //10.使用hasOwnProperty方法
    if(!this.hasOwnProperty('myObj8')){ console.log("8"); this.myObj8 = {}; }
  • 相关阅读:
    day02-数据库操作
    day01-MySQL介绍
    3-socketserver
    1-多线程与多进程
    keyword模块
    math模块
    查看进程pid与ppid
    开启进程的两种方式
    进程理论
    进程
  • 原文地址:https://www.cnblogs.com/zhutianpeng/p/3461488.html
Copyright © 2011-2022 走看看