This article is 1.2 JS-typeof simplified memory version, for the form of interview questions, if you do not understand, please move to the original.
1. What are the characteristics of typeof judgment data types?
A:
- For primitive types, all but NULL returns the correct result.
- For reference types, return object all but function.
- For NULL, return type Object.
- Return function type for function.
Ex. :
typeof 1 // 'number'
Copy the code
2. What are the methods for determining data types? What are their characteristics?
A:
instanceof
The prototype chain is used to determine whether A is an instance of B, and the expression is:A instanceof B
, instanceof must be the object type, and the case is correct. Return true/false. case
[] instanceof Array;// true
Copy the code
Object.prototype.toString.call()
Write the type of data to be determined in () to be similar"[object String]"
Returns the corresponding type as a string. Ex. :
Object.prototype.toString.call(' ');// [object String]
Copy the code
jquery.type()
Writes the data of the type to be determined in () and returns the corresponding lowercase string. Ex. :
jQuery.type( undefined );// "undefined"
Copy the code
- Normally typeof will do; When it is necessary to determine whether the Object type is a predictive type, for example, whether [] is Array, instanceof is used. As long as it’s not too much trouble, prototype and jquery.type() work in all cases.