JavaScript type detection method example tutorial

JavaScript type detection method example tutorial

Preface

JavaScript is one of the widely used languages ​​in the web front end, and it has an irreplaceable position in many fields such as web application production, script production, and small programs. The author has studied the front-end for some time and feels that the JS knowledge points are quite complicated, so he records some of the knowledge, thoughts and insights he has learned.

JS Basic Types

JavaScript's basic types are divided into primitive basic types and reference data types:

Primitive basic types:

  • number
  • string
  • boolean
  • null
  • undefined
  • symbol

Reference data types:

  • Object
  • Function
  • Array
  • Date
  • RegExp

Note: There is no symbol type in ES5

Type Detection

There are five common methods for type detection:

  1. typeof
  2. instanceof
  3. Object.prototype.toString
  4. constructor
  5. duck type

1.typeof determines the basic type

The type names returned by the keyword typeof include only the following 7 types: number, string, boolean, undefined, symbol, object, function.

Null and most reference types cannot be judged using typeof.

let num = 32
let str = "32"
let bool = true
let nul = null
let undef = undefined
let sym = Symbol()

const obj = new Object()
const arr = new Array()
const fun = new Function()
const date = new Date()
const reg = new RegExp()

console.log(typeof num) //number
console.log(typeof str) //string
console.log(typeof bool) //boolean
console.log(typeof nul) //object
console.log(typeof undef) //undefined
console.log(typeof sym) //symbol

console.log(typeof obj) //object
console.log(typeof arr) //object
console.log(typeof fun) //function
console.log(typeof date) //object
console.log(typeof reg) //object

Note: When using typeof to judge null, Array, Date, RegExp, etc., the results are all object

2.instanceof determines the reference data type

Instanceof uses the __proto__ property of the variable to point to the prototype property of the prototype for type judgment. It should be noted that if the direct assignment method is used for basic data types, the __proto__ property does not exist and we need to use the constructor.

const obj = new Object()
const arr = new Array()
const fun = new Function()
const date = new Date()
const reg = new RegExp()

console.log(obj instanceof Object) //true
console.log(arr instanceof Array) //true
console.log(fun instanceof Function) //true
console.log(date instanceof Date) //true
console.log(reg instanceof RegExp) //true

let num1 = 32
let num2 = new Number(32)
console.log(num1 instanceof Number) //false
console.log(num2 instanceof Number) //true

In addition, although instanceof can determine that arr is an instance of Array, it also thinks it is an instance of Object, which is not friendly for determining an unknown reference type.

const arr = new Array()
console.log(arr instanceof Array) //true
console.log(arr instanceof Object) //true

The reason is that the __proto__ property of arr.__proto__ points to the prototype object of Object.

In this case, you can use the constructor to make the judgment.

Note: instanceof cannot be used for object detection between different windows or iframes!

3. Object.prototype.toString determines the type

toString() is the prototype method of Object. Every object that inherits Object has a toString method.

All objects whose typeof returns a value of object contain an internal property [[class]], which cannot be accessed directly and is usually viewed through Object.prototype.toString().

If the toString method is not overridden, it returns the [[Class]] of the current object by default, in the format of [object Xxx], where Xxx is the type of the object. However, except for objects of type Object, when other types directly use the toString method, a string containing the content will be directly returned, so we need to use the call or apply method to change the execution context of the toString method.

let num = 32
let str = "32"
let bool = true
let nul = null
let undef = undefined
let sym = Symbol()

const obj = new Object()
const arr = new Array()
const fun = new Function()
const date = new Date()
const reg = new RpgExp()

console.log(Object.prototype.toString.apply(num)) //"[object Number]"
console.log(Object.prototype.toString.apply(str)) //"[object String]"
console.log(Object.prototype.toString.apply(bool)) //"[object Boolean]"
console.log(Object.prototype.toString.apply(nul)) //"[object Null"
console.log(Object.prototype.toString.apply(undef)) //"[object Undefined]"
console.log(Object.prototype.toString.apply(sym) //"[object Symbol]"

console.log(Object.prototype.toString.call(obj)) //"[object Object]"
console.log(Object.prototype.toString.call(arr)) //"[object Array]"
console.log(Object.prototype.toString.call(fun)) //"[object Function]"
console.log(Object.prototype.toString.call(date)) //"[object Date]"
console.log(Object.prototype.toString.call(reg) //"[object RegExp]"

Object.prototype.toString can determine null, but we usually use null===null to determine whether it is null.

4. Constructor determines the type

The constructor property returns the constructor of the variable. Of course, you can also use string interception to obtain the constructor name for judgment to obtain a Boolean value, such as " ".constructor === String.

let num = 32
let str = "32"
let bool = true
let nul = null
let undef = undefined
let sym = Symbol()

const object = new Object()
const arr = new Array()
const fun = new Function()
const date = new Date()
const reg = new RegExp()

console.log(num.constructor) //ƒ Number() { [native code] }
console.log(str.constructor) //ƒ String() { [native code] }
console.log(bool.constructor) //ƒ Boolean() { [native code] }
console.log(nul.constructor) //Uncaught TypeError: Cannot read property 'constructor' of null
console.log(undef.constructor) //Uncaught TypeError: Cannot read property 'constructor' of undefined
console.log(sym.constructor) //ƒ Symbol() { [native code] }

console.log(obj.constructor === Object) //true
console.log(arr.constructor === Array) //true
console.log(fun.constructor === Function) //true
console.log(date.constructor === Date) //true
console.log(reg.constructor === RegExp) //true

The constructor cannot be used to determine null and undefined, but it can be avoided when using instanceof. The prototype object of arr can be either Array or Object.

5. duck type uses features to determine type

In programming, duck typing is a style of dynamic typing. In this style, the effective semantics of an object is not determined by inheriting from a specific class or implementing a specific interface, but by the "current set of methods and properties".

“When you see a bird that walks like a duck, swims like a duck, and quacks like a duck, then that bird can be called a duck.”

In duck typing, the focus is on the behavior of the object, what it can do; rather than on the type of the object.

For example, in a language that doesn't use duck typing, we could write a function that takes an object of type "duck" and calls its "walk" and "quack" methods.

Later, in a function that uses duck typing, you can accept an object of any type and call its "walk" and "quack" methods. If the methods that need to be called do not exist, a runtime error will be raised. Any object with the correct "go" and "call" methods will be accepted by this function.

For example, to determine whether an object is an array, you can see whether the object has methods such as push().

Summarize

This is the end of this article about JavaScript type detection. For more relevant JavaScript type detection content, please search 123WORDPRESS.COM’s previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of data type issues in JS array index detection
  • Detailed explanation of data types in JavaScript and how to detect data types
  • Detailed explanation of data type detection methods in javascript
  • Summary of js data type detection
  • js learning summary_Four methods based on data type detection (must read)
  • Summary of JS methods for detecting array types
  • Summary of several ways to detect data types in javascript
  • Summary of JavaScript basic data types and common methods of type detection
  • Summary of several ways to detect data types in JS and their advantages and disadvantages
  • JS regular expression matching detection of various numeric types (digital verification)
  • How to detect various types of JavaScript
  • JavaScript type detection: defects and optimization of typeof and instanceof
  • JavaScript learning notes: Detecting client type (engine, browser, platform, operating system, mobile device)
  • Javascript implements detection of client type code package
  • JavaScript method to detect the type of file

<<:  How to implement interception of URI in nginx location

>>:  MySQL 5.7.20 Green Edition Installation Detailed Graphic Tutorial

Recommend

Four categories of CSS selectors: basic, combination, attribute, pseudo-class

What is a selector? The role of the selector is t...

Let’s take a look at JavaScript precompilation (summary)

JS running trilogy js running code is divided int...

MySQL 8.0.12 decompression version installation tutorial personal test!

Mysql8.0.12 decompression version installation me...

Introduction to Sublime Text 2, a web front-end tool

Sublime Text 2 is a lightweight, simple, efficien...

Solve the problem that Docker must use sudo operations

The steps are as follows 1. Create a docker group...

Analysis of MySQL query sorting and query aggregation function usage

This article uses examples to illustrate the use ...

How to perfectly implement the grid layout with intervals on the page

Typical layout examples As shown in the above pic...

JavaScript implements draggable modal box

This article shares the specific code of JavaScri...

MySQL online log library migration example

Let me tell you about a recent case. A game log l...

Complete steps to quickly configure HugePages under Linux system

Preface Regarding HugePages and Oracle database o...

Learning to build React scaffolding

1. Complexity of front-end engineering If we are ...

How to deploy FastDFS in Docker

Install fastdfs on Docker Mount directory -v /e/f...

How to get the contents of .txt file through FileReader in JS

Table of contents JS obtains the .txt file conten...