typeof all Return Object
All data types in JavaScript are strictly objects, but in practice we still have types, if we want to determine whether a variable is an array or an object using TypeOf, because it all returns object
Copy Code code as follows:
var o = {' name ': ' Lee '};
var a = [' reg ', ' Blue '];
document.write (' O typeof is ' + typeof O);
document.write (' <br/> ');
document.write (' A typeof is ' + typeof a);
Perform:
Copy Code code as follows:
O typeof is Object
A typeof is Object
Therefore, we can only discard this method, to determine that there are two methods of array or object
First, use the TypeOf plus length property
The array has a length property, the object is not, and the TypeOf array and object are returned object, so we can judge
Copy Code code as follows:
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, using instanceof
Use instanceof to determine whether a variable is not an array, such as:
Copy Code code as follows:
var o = {' name ': ' Lee '};
var a = [' reg ', ' Blue '];
Alert (a instanceof Array); True
Alert (o instanceof Array); False
or whether it belongs to the object.
Copy Code code as follows:
var o = {' name ': ' Lee '};
var a = [' reg ', ' Blue '];
Alert (a instanceof Object); True
Alert (o instanceof Object); True
But the array is also object, so the above two are true, so we want to use instanceof to judge whether the data type is an object or an array, we should prioritize the array, and finally judge the object
Copy Code code as follows:
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 prioritize array, for example:
Copy Code code as follows:
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 is also judged to be object.