In the basis of front-end interview, type judgment is often a knowledge point. The following summarizes the basic uses of Typeof and Instanceof, as well as other types. Please note 😀😀😀 if any errors are omitted
The typeof keyword
typeof 'asd'; // -> "string" typeof {} ; // -> "object" typeof []; // -> "object"Copy the code
Typeof can be used to determine Undefined, Null, String, Number, Boolean, Function, BigInt, Symbol, and Object. In particular, typof can be used as a Function, but other objects, including Array, can only be used as objects. So typeof is good for determining base types.
So, if you want to identify other object types that are commonly used, like Array, what are the methods?
Judge Array
-
In ES5.1, the isArray method is provided for Array objects, but be aware of its compatibility.
Array.isArray([]); // -> true Copy the code
-
As can be seen in the MDN documentation, isArray can be written as follows, so the second method is to use object.protoype.tostring to determine:
if(! Array.isArray) { Array.isArray =function(arg) { return Object.prototype.toString.call(arg) === '[object Array]'; }; } Copy the code
-
When learning JS, I also know that there is another keyword instanceof which is often used to determine types. I think MDN’s explanation of its role is the most clear 👇
The instanceof operator is used to check whether the constructor’s prototype property appears on the prototype chain of an instance object.
So the third way to figure out what an array is
[] instanceof Array; / / = >true Copy the code
-
Following the principle of the above method, we can wonder if we can use constructor (each object has a constructor property that points to the constructor of that instance object).
[].constructor === Array; / / = >true Copy the code
However, using constructor is definitely not rigorous because the constructor property can be overridden and the Array object has an Array on its prototype chain, but is not necessarily instantiated by Array.
Identify other objects
From a few ways to judge arrays, we can fully use Object.protoype.tostring or instanceof to judge other built-in objects. Object. Protoype. ToString: String, Number, Boolean, Undefined, Null, Array, Date, Error, RegExp, Function, Math, JSON, I have never tried anything else.