preface

In Web development, we often encounter scenarios where we need to determine whether data is a string or a number, and whether data is an array or an object. Let’s take a look at JavaScript methods for determining data types.

Welcome to follow my wechat official account: FrontGeek

typeof

In JS, the most common judgment method is naturally typeof.

Typeof: is a unary operator that precedes its single operand, which can be of any type. The return value is a string representing the operand type.

In ES5, JavaScript has six data types: Number, String, Boolean, Undefined, Null, and Object. ES6 adds a new data type: Symbol.

Typeof = typeof; typeof = typeof;

console.log(typeof 1) // number
console.log(typeof 'test') // string
console.log(typeof true) // boolean
console.log(typeof undefined) // undefined
console.log(typeof null) // object
console.log(typeof {}) // object
console.log(typeof []) // object
console.log(typeof Symbol()) // symbol
Copy the code

Null and object all return object, and the others all return lowercase strings corresponding to the data type.

In JS, the Object type is subdivided into many types, such as Array, Function, Date, Error, etc. We also use typeof to try to determine these types:


console.log(typeof []) // object
function a(){}
console.log(typeof a) // function
let now = new Date(a)console.log(typeof now) // object
let error = new Error(a)console.log(typeof error) // object
Copy the code

Typeof can detect function types, other types return object, there is no way to determine which subtype.

instanceof

The instanceof operator is used to check whether an object belongs to a particular class. It also considers inheritance.

Usage:

A instanceof B
Copy the code

Indicates whether A is an instance of B, returning true if so and false otherwise.

Let’s start with a few examples of instanceof:

console.log([] instanceof Array) // true
console.log([] instanceof Object) // true

console.log({} instanceof Object) // true

console.log(new Date(a)instanceof Date) // true

function a (){}
console.log(a instanceof Function) // true
console.log(new a() instanceof a) // true
Copy the code

From the above we can see that instanceof can determine that [] is an instanceof Array, but it also considers [] to be an instanceof Object.

Let’s briefly analyze the relationship among [], Array and Object:

[].proto points to array. prototype, array.prototype. proto points to Object.prototype, and object.prototype. proto points to null, marking the end of the prototype chain. Therefore, [], Array, and Object form a chain of prototypes internally.

We can see from the prototype chain that the proto of [] points directly to array. prototype and indirectly to object. prototype, so according to the judgment rule of instanceof, [] is the instanceof Object. Similarly, similar new Date() and new Person() will also form a corresponding prototype chain. Therefore:

Instanceof can only be used to determine whether two objects belong to the instance relationship, but not the specific type of an object instance.

constructor

In addition to instanceof, we can also use the constructor property of an object to determine its subtypes.

The constructor property represents the association between the stereotype object and the constructor. If the stereotype object is modified, the constructor property is generally modified at the same time to prevent errors when referencing it. Therefore, when modifying a prototype object, you generally modify the point to the constructor property as well.

console.log('22'.constructor === String)             // true
console.log(true.constructor === Boolean)            // true
console.log([].constructor === Array)                // 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
Copy the code

We need to note the following when using constructor:

  • Null and undefined have no constructors and therefore have no constructor, and both types need to be judged in other ways;
  • Constructor is unstable. This is mainly true of custom objects. When developers rewrite Prototype, the original constructor reference is lost and constructor defaults to Object

Object.prototype.toString

ToString () is a prototype method for Object that, by default, returns the current Object’s [[Class]]. [[Class]] is an internal property in the form of [object Xxx], where Xxx is the type of the object.

For Object objects, calling toString directly returns Object Object. For other objects, call call/apply to return the correct type information.

Let’s look at a demo:

console.log(Object.prototype.toString.call(' '))   // [object String]
console.log(Object.prototype.toString.call(1))    // [object Number]
console.log(Object.prototype.toString.call(true)) // [object Boolean]
console.log(Object.prototype.toString.call(Symbol())) //[object Symbol]
console.log(Object.prototype.toString.call(undefined)) // [object Undefined]
console.log(Object.prototype.toString.call(null)) // [object Null]
console.log(Object.prototype.toString.call(new Function())) // [object Function]
console.log(Object.prototype.toString.call(new Date())) // [object Date]
console.log(Object.prototype.toString.call([])) // [object Array]
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({})) // [object Object]
console.log(Object.prototype.toString.call(Math)) // [object Math]
console.log(Object.prototype.toString.call(JSON)) // [object JSON]

function a () {
  console.log(Object.prototype.toString.call(arguments)) // [object Arguments]
}
a()
Copy the code

Object. The prototype. ToString appears to be an artifact, versatility, but more complicated compared with several other methods, in the actual development process, we may judge the encapsulated into a type of function calls.

type API

Math, JSON, and Arguments are not checked during actual development, so isType functions are not considered.

Encapsulation results are as follows:

function isType(value, type) {
  return Object.prototype.toString.call(value) === `[object ${type}] `
}
console.log(isType('111'.'String')) // true
console.log(isType(null.'Null')) // true
Copy the code

conclusion

When you want to judge a basic typeof data, you can use typeof. It is simple and reliable. When you want to determine which subtype an object belongs to, you can use the instanceof operator or the constructor property, but you need to have an expected type, or you’ll need to write a different if for each type. else… Statement. Another point to note is that the constructor property can be modified so it is not reliable; Capacity is much, if you don’t too code requires accurate and comprehensive, and then you can use the Object. The prototype. ToString. Call the judgement ().

For all example codes in this document, see judge-type-of-data

If you find this helpful:

1. Click “like” to support it, so that more people can see this article

2, pay attention to the public account: FrontGeek technology (FrontGeek), we learn and progress together.