typeof all returns object
All data types in JavaScript are objects in the strict sense, but in actual use we still have types. If you want to determine whether a variable is an array or an object, you can’t use typeof because it all returns object
var o = { 'name':'lee' };
var a = ['reg','blue'];
document.write( ' o typeof is ' typeof o);
document.write( '
');
document.write( ' a typeof is ' typeof a);
Execution:
o typeof is object
a typeof is object
Therefore, we can only give up this method. There are two ways to determine whether it is an array or an object
First, use typeof plus length attribute
Array has length attribute, object does not, and typeof array and object both return object, so we can judge this way
var o = { 'name':'lee' };
var a = ['reg','blue'];
var getDataType = function(o){
If(typeof o == 'object'){
If( typeof o.length == 'number' ){
return 'Array';
}else{
return 'Object';
}
}else{
return 'param is no object type';
}
};
alert( getDataType(o) ); // Object
alert( getDataType(a) ); // Array
alert( getDataType(1) ); // param is no object type
alert( getDataType(true) ); // param is no object type
alert( getDataType('a') ); // param is no object type
Second, use instanceof
Use instanceof to determine whether a variable is an array, such as:
var o = { 'name':'lee' };
var a = ['reg','blue'];
alert( a instanceof Array ); // true
alert( o instanceof Array ); // false
You can also determine whether it belongs to object
var o = { 'name':'lee' };
var a = ['reg','blue'];
alert( a instanceof Object ); // true
alert( o instanceof Object ); // true
But arrays also belong to objects, so both of the above are true. Therefore, when we use instanceof to determine whether the data type is an object or an array, we should first determine array, and finally determine object
var o = { 'name':'lee' };
var a = ['reg','blue'];
var getDataType = function(o){
If(o instanceof Array){
return 'Array'
}else if( o instanceof Object ){
return 'Object';
}else{
return 'param is no object type';
}
};
alert( getDataType(o) ); // Object
alert( getDataType(a) ); // Array
alert( getDataType(1) ); // param is no object type
alert( getDataType(true) ); // param is no object type
alert( getDataType('a') ); // param is no object type
If you don’t judge Array first, for example:
var o = { 'name':'lee' };
var a = ['reg','blue'];
var getDataType = function(o){
If(o instanceof Object){
return 'Object'
}else if( o instanceof Array ){
return 'Array';
}else{
return 'param is no object type';
}
};
alert( getDataType(o) ); // Object
alert( getDataType(a) ); // Object
alert( getDataType(1) ); // param is no object type
alert( getDataType(true) ); // param is no object type
alert( getDataType('a') ); // param is no object type
Then the array will also be judged as object.