Preface
This article covers basic knowledge and js data types. We all know that php has the is_array () function, but js does not. When we determine whether the data type is an array, we can write a function to determine whether it is safe. Today, some basic data type judgment methods are popularized, and we hope to help you.
Typeof
When typeof is used for many times, it is used to determine whether a global variable is absent. If a page defines a global variable. If you make the following judgment:
// Haorooms is a global variable
If (haorooms! = Undefined ){
} // Js will report an error, saying "Uncaught ReferenceError: haorooms is not defined"
The solution is as follows:
If (typeof haorooms! = Undefined ){
}
If typeof is used, no error will be reported! This is one of the typeof applications!
In addition, typeof can also be used to determine the data type! As follows:
Var haorooms = "string"; console. log (haorooms); // string
Var haorooms = 1; console. log (haorooms); // number
Var haorooms = false; console. log (haorooms); // boolean
Var haorooms; console. log (typeof haorooms); // undfined
Var haorooms = null; console. log (typeof haorooms); // object
Var haorooms = document; console. log (typeof haorooms); // object
Var haorooms = []; console. log (haorooms); // object
Var haorooms = function () {}; console. log (typeof haorooms) // function can be used to determine the data type and function type.
Obviously, for typeof, except for the first four types, null, objects, and arrays all return object types;
Instanceof
You can use it to determine whether it is an array.
Var haorooms = [];
Console. log (haorooms instanceof Array) // return true
Constructor
Constructor is the constructor corresponding to the returned object.
Methods for judging various data types:
Console. log ([]. constructor = Array );
Console. log ({}. constructor = Object );
Console. log ("string". constructor = String );
Console. log (123). constructor = Number );
Console. log (true. constructor = Boolean );
Function employee (name, job, born ){
This. name = name;
This. job = job;
This. born = born ;}
Var haorooms = new employee ("Bill Gates", "Engineer", 1985 );
Console. log (haorooms. constructor); // output function employee (name, jobtitle, born) {this. name = name; this. jobtitle = job; this. born = born ;}
By outputting haorooms. constructor, we can see that constructor is the constructor corresponding to the returned object.