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

Ubuntu MySQL version upgraded to 5.7

A few days ago, the library said that the server ...

The correct way to migrate MySQL data to Oracle

There is a table student in the mysql database, i...

Using Docker to create static website applications (multiple ways)

There are many servers that can host static websi...

Recommended tips for web front-end engineers

Let's first talk about the value of web front...

How to install multiple mysql5.7.19 (tar.gz) files under Linux

For the beginner's first installation of MySQ...

MySQL statement execution order and writing order example analysis

The complete syntax of the select statement is: S...

Summary of Spring Boot Docker packaging tools

Table of contents Spring Boot Docker spring-boot-...

CSS menu button animation

To write a drop-down menu, click the button. The ...

Detailed explanation of JavaScript function introduction

Table of contents Function Introduction function ...

What to do if the container started by docker run hangs and loses data

Scenario Description In a certain system, the fun...

Detailed explanation of HTML basics (Part 2)

1. List The list ul container is loaded with a fo...

Avoid abusing this to read data in data in Vue

Table of contents Preface 1. The process of using...

A Brief Analysis of MySQL PHP Syntax

Let's first look at the basic syntax of the c...

Analysis of common usage examples of MySQL process functions

This article uses examples to illustrate the comm...