1, the typeof
Typeof can be used to check whether a variable is a primitive data type. The Typeof operator is the best tool for determining whether a variable is a string, value, Boolean, or undefined. If the variable value is an object or null, typeof returns “object”;
var s = "Nicholas";
var b = true;
var i = 22;
var u;
var n = null;
var o = new Object();
alert(typeof s); //string
alert(typeof i); //number
alert(typeof b); //boolean
alert(typeof u); //undefined
alert(typeof n); //object
alert(typeof o); //object
Copy the code
2, instanceof
Instanceof can be used to check whether a variable is of a reference data type. If the variable is of a given reference type (identified by its stereotype chain; The instanceof operator returns true, as shown in Chapter 6. Look at the following example:
alert(person instanceof Object); // Is the person variable Object? alert(colors instanceof Array); // Is the variable colors Array? alert(pattern instanceof RegExp); // Is the variable pattern RegExpCopy the code
- Note: By regulation, all values of reference types are instances of Object. Therefore, the instanceof operator always returns true when detecting a reference type value and the Object constructor. Of course, if you use the instanceof operator to detect a value of a primitive type, it will always return false because the primitive type is not an object.