Detailed explanation of four methods for judging JavaScript type

  • 2021-08-31 07:18:55
  • OfStack

JavaScript has eight built-in types, which are collectively referred to as "basic types" except objects.

Null (null) Undefined (undefined) Boolean (boolean) Digital (number) String (string) Object (object) Symbol (added in symbol, ES6) Large integer (BigInt, ES2020 introduced)

Symbol: A primitive data type introduced in ES6, which represents a value with only 1 but no 2.

BigInt is a new data type introduced by ES2020, which is used to solve the problem that the numbers in JavaScript can only reach 53 binary bits (JavaScript all numbers are saved as 64-bit floating-point numbers, which are larger than integers in this range and cannot be accurately represented. For details, please see: New data types-BigInt

1. typeof

typeof is an operator, not a function, followed by a 1-yuan expression to the right, and returns the data type of this expression. The returned results are expressed in the form of strings of this type (all lowercase letters), including the following eight types: number, boolean, symbol, string, object, undefined, function, bigInt and so on.

The principle of typeof is that different objects are represented as binary in the bottom layer, and the first (lower) 3 bits of binary in Javascript store their type information.

000: Object 010: Floating point number 100: String 110: Boolean 1: Integer

console.log(typeof undefined) // undefind
console.log(typeof null)   // object
console.log(typeof true)   // boolean
console.log(typeof 43)    // number
console.log(typeof '21')   // string
console.log(typeof {a:1})   // object
console.log(typeof Symbol()) // symbol
console.log(typeof 123n)   // bigint
function a() {}
console.log(typeof a)     // function
var date = new Date()
var error = new Error()
console.log(typeof date)   // object
console.log(typeof error)   // object

2. instanceof

instanceof is used to judge whether A is an instance of B, and the expression is A instanceof B. If A is an instance of B, true is returned, otherwise false is returned. Special attention should be paid here: instanceof detects prototypes

Generally speaking, instanceof is used to compare whether an object is an instance of a constructor. Note that instanceof can accurately judge complex data types, but cannot correctly judge basic data types


console.log(12 instanceof Number) // false
console.log('22' instanceof String) // false
console.log(true instanceof Boolean) // false
console.log(null instanceof Object) // false
console.log(undefined instanceof Object) // false
 
console.log([] instanceof Array)  // true
console.log({a: 1} instanceof Object) // true
console.log(json instanceof Object) // true
function a() {}
console.log(a instanceof Function) // true
console.log(new Date() instanceof Date) //true
console.log(reg instanceof RegExp) //true
console.log(error instanceof Error) // true

3. Object.prototype.toString.call()

toString () is the prototype method of Object, which is called and returns the [[Class]] of the current object by default. This is an internal property in the format [object Xxx], where Xxx is the type of the object.

For an Object object, a direct call to toString () returns [object Object]. For other objects, you need to call through call/apply to return the correct type information.


console.log(Object.prototype.toString.call(1))     // [object Number]
console.log(Object.prototype.toString.call(1n))     // [object BigInt]
console.log(Object.prototype.toString.call('123'))   // [object String]
console.log(Object.prototype.toString.call(true))    // [object Boolean]
console.log(Object.prototype.toString.call(undefined)) // [object Undefined]
console.log(Object.prototype.toString.call(null))    // [object Null]
console.log(Object.prototype.toString.call({}))     // [object Object]
console.log(Object.prototype.toString.call([]))     // [object Array]
console.log(Object.prototype.toString.call(function a() {})) // [object Function]
console.log(Object.prototype.toString.call(Symbol()))     // [object Symbol]
console.log(Object.prototype.toString.call(Math))       // [object Math]
console.log(Object.prototype.toString.call(JSON))       // [object JSON]
console.log(Object.prototype.toString.call(new Date()))    // [object Date]
console.log(Object.prototype.toString.call(new RegExp()))   // [object RegExp]
console.log(Object.prototype.toString.call(new Error))    // [object Error]
console.log(Object.prototype.toString.call(window)      // [object Window]
console.log(Object.prototype.toString.call(document)     // [object HTMLDocument]

Using this method, we can encapsulate an isType method to determine the type


let isType = (type, obj) => {
  return Object.prototype.toString.call(obj) === `[object ${type}]`
}
console.log(isType('Number', 12))  // true
console.log(isType('Number', '12')) // false

Or


let type = function(o) {
  let s = Object.prototype.toString.call(o);
  return s.match(/\[object (.*?)\]/)[1].toLowerCase();
};
console.log(type(12)) // number
console.log(type('12')) // string
console.log(type({})) // object
console.log(type([])) // array

4. constructor

constructor property, you can know an instance object, in the end which 1 constructor produced.

constructor attribute indicates the relationship between prototype object and constructor. If prototype object is modified, constructor attribute will be modified at the same time to prevent errors in reference. Therefore, when modifying prototype objects, 1 generally modifies the pointing of constructor attributes at the same time.


console.log('22'.constructor === String)       // true
console.log(true.constructor === Boolean)      // true
console.log([].constructor === Array)        // true
console.log(document.constructor === HTMLDocument)  // true
console.log(window.constructor === Window)      // true
console.log(new Number(22).constructor === Number)  // true
console.log(new Function().constructor === Function) // true
console.log((new Date()).constructor === Date)    // true
console.log(new RegExp().constructor === RegExp)   // true
console.log(new Error().constructor === Error)    // true

Note:

1. null and undefined are invalid objects, so there will be no constructor. These two types of data need to be judged in other ways.

2. The constructor of the function is unstable, which is mainly reflected in the custom object. When the developer rewrites prototype, the original constructor reference will be lost, and constructor will default to Object

The above is the JavaScript type judgment of the 4 methods of detail, more information about JavaScript type judgment, please pay attention to other related articles on this site!


Related articles: