In js, a variable is expected to be an object. How can you tell whether this variable is an object or not?

assume that I need to get the house object from the background data and process the house object if the house object exists. Is it appropriate for me to deal with it like this?

var obj = data.house;//data

if(obj){
    //
}

what about this way?

var obj = data.house;//data

if(typeof obj != undefined){
    //
}
May.22,2021

if(data.hasOwnProperty('house'){
    var obj = data.house;
}

Note that typeof null = "object" ;
you can use Object.prototype.toString.call (null). Slice (8,-1). ToLowerCase () to get specific type


data & data.house


if(obj instanceof Object)

you can use this method, but if this value is undefined, it will report an error. It is recommended to use the following two methods:

1. Use the in operator
if ("house" in data) {}

)

2. Use the hasOwnProperty method
if (data.hasOwnProperty ("house")) {}

where the attributes on the prototype chain cannot be determined on the hasOwnProperty

Menu