Four data type judgment methods in JS

Four data type judgment methods in JS

This article summarizes four judgment methods:

1. typeof

typeof is an operator that can be used in two ways :(1)typeof (expression); (2)typeof variable name; the return value is a string that describes the data type of the variable; so it can be used to determine the seven types of number , string , object , boolean , function , undefined , and symbol The content returned in each case is shown in the following table:

// string console.log(typeof('lili')); // string 
// number console.log(typeof(1)); // number 
// Boolean value console.log(typeof(true)); // boolean 
// undefined 
console.log(typeof(undefined)); // undefined 
// object console.log(typeof({})); // object 
// array console.log(typeof([])); // object 
// null 
console.log(typeof(null)); // object 
// function console.log(typeof(() => {})); // function 
// Symbol value console.log(typeof(Symbol())); // symbol 

2. instanceof

instanceof operator is used to detect whether prototype property of the constructor appears on the prototype chain of an instance object. The return value is a Boolean value, which is used to indicate whether a variable belongs to an instance of an object. Its syntax is as follows:

object instanceof constructor 

const arr = [1, 2]; 
// Check if Object's prototype is in the prototype chain of the array console.log(arr instanceof Object); // true 
// Prototype of array arr const proto1 = Object.getPrototypeOf(arr); 
console.log(proto1); // [] 
// The prototype of the prototype of array arr const proto2 = Object.getPrototypeOf(proto1); 
console.log(proto2); // [] 
//Object's prototype 
console.log(Object.prototype); 
// Check if the prototype of arr is equal to the prototype of Object console.log(proto1 === Object.prototype); // false 
// Check if the prototype of arr's prototype is equal to Object's prototype console.log(proto2 === Object.prototype); // true 
 


3. Constructor

This judgment method actually involves the relationship between prototypes, constructors, and instances. A more in-depth explanation will be given later. Below you only need to briefly understand the relationship between these three.

When defining a function (constructor), the JS engine will add a prototype to it. The prototype has a corresponding constructor property pointing to the constructor, so that the prototype and the constructor know each other. When the constructor is instantiated, a corresponding instance is generated. The instance can access constructor property on the corresponding prototype, so that the instance can understand who generated it, and thus understand the data type of the new object after it is generated.

const val1 = 1; 
console.log(val1.constructor); // [Function: Number] 
const val2 = 'abc'; 
console.log(val2.constructor); // [Function: String] 
const val3 = true; 
console.log(val3.constructor); // [Function: Boolean] 


Although this method can determine its data type, it has two disadvantages:

  • null and undefined are invalid objects, so there will be no constructor . These two types of data need to be judged by other means.
  • constructor of a function is unstable. This is mainly reflected in custom objects. When the developer rewrites prototype , the original constructor reference will be lost and constructor will default to Object

4. toString()

toString() is the prototype method of Object . When this method is called, [[Class]] of the current object is returned by default. This is an internal property with the format [object Xxx] where Xxx is the type of the object. Therefore, Object.prototype.toString() method can be used to make a more accurate judgment on the type of the variable.

The results returned by this type for different variable types are as follows:

It is easy to construct a type identification function using this method. The code is as follows:

function type(target) { 
    const ret = typeof(target); 
    const template = { 
        "[object Array]": "array",  
        "[object Object]":"object", 
        "[object Number]":"number - object", 
        "[object Boolean]":"boolean - object", 
        "[object String]":'string-object' 
    } 
    if(target === null) { 
        return 'null'; 
    } 
    else if(ret == "object"){ 
        const str = Object.prototype.toString.call(target); 
        return template[str]; 
    } 
    else{ 
        return ret; 
    } 
} 

console.log(type({})); // object 
console.log(type(123)); // number 
console.log(type('123')); // string 

This concludes this article about the four data type judgment methods in JS. For more information about data type judgment methods in JS, please search previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Summary of 4 methods for determining data types in js and jquery
  • 4 ways to determine data types in JavaScript
  • js data type judgment method
  • js data types and their judgment method examples
  • Examples of correct judgment methods for data types in JS
  • Four methods of using JS to determine data types
  • Share several methods of JavaScript type judgment

<<:  MySQL paging query optimization techniques

>>:  Solution to the problem that mixin does not work in scss (browser cannot compile it)

Recommend

About CSS floating and canceling floating

Definition of Float Sets the element out of the n...

How to implement Echats chart large screen adaptation

Table of contents describe accomplish The project...

How to export CSV file with header in mysql

Refer to the official document http://dev.mysql.c...

Introduction to fuzzy query method using instr in mysql

Using the internal function instr in MySQL can re...

How to handle the tcp_mark_head_lost error reported by the Linux system

Problem Description Recently, a host reported the...

js canvas realizes circular water animation

This article example shares the specific code of ...

Navigation Design and Information Architecture

<br />Most of the time when we talk about na...

MySQL 8.0.12 decompression version installation tutorial personal test!

Mysql8.0.12 decompression version installation me...

Simple steps to create a MySQL container with Docker

Preface We have already installed Docker and have...

25 Tools to Improve Website Usability and Conversion Rates

For a website, usability refers to whether users c...

Why is it not recommended to use index as key in react?

1. Compare the old virtual DOM with the new virtu...

A brief discussion on the lazy loading attribute pattern in JavaScript

Table of contents 1. Introduction 2. On-demand at...