How to check if a variable is loaded in JavaScript?

后端 未结 10 1841
遇见更好的自我
遇见更好的自我 2021-01-31 04:01

How do I see if a certain object has been loaded, and if not, how can it be loaded, like the following?

if (!isObjectLoaded(someVar)) {
    someVar= loadObject()         


        
10条回答
  •  灰色年华
    2021-01-31 04:47

    If by loaded you mean defined, you can check the type of the variable with the typeof function. HOWEVER typeof has a few quirks, and will identify an Object, an Array, and a null as an object

    alert(typeof(null));
    

    Identifying a null as a defined object would probably cause your program to fail, so check with something like

    if(null !== x && 'object' == typeof(x)){
        alert("Hey, It's an object or an array; good enough!");
    }
    

提交回复
热议问题