Examples of correct judgment methods for data types in JS

Examples of correct judgment methods for data types in JS

Preface

Javascript is a dynamically typed language. From declaration to final use, a variable may go through many functions, and the data type may also change. Therefore, it is particularly important to judge the data type of a variable.

Can typeof correctly determine the type?

typeof is an operator that takes a unary expression on its right side and returns the data type of that expression. The returned result is expressed in the form of a string of that type (all lowercase letters), including the following 7 types: number, boolean, symbol, string, object, undefined, function, etc.

Due to historical reasons, typeof null is equal to object when judging primitive types. Moreover, objects and arrays will be converted into objects. Here are some examples:

    typeof 1 // 'number'
    typeof "1" // 'string'
    typeof null // 'object'
    typeof undefined // 'undefined'
    
    typeof [] // 'object'
    typeof {} // 'object'
    typeof function() {} // 'function'

So we can find that typeof can determine basic data types, but it is difficult to determine complex data types other than functions. So we can use the second method, which is usually used to determine complex data types, and can also be used to determine basic data types.

For the return value of object, there are three cases:

  • Value is null
  • Value is object
  • Value is array

For null, we can directly use === to make a judgment, but what about arrays and objects? Don’t worry, let’s continue.

Can instanceof correctly determine the type?

Instanceof is used to determine whether A is an instance of B. The expression is: A instanceof B. If A is an instance of B, it returns true, otherwise it returns false.

Instanceof is judged by the prototype chain, but for objects, Array will also be converted into Object, and it cannot distinguish between basic types string and boolean. You can put the content you want to judge on the left and the type on the right to perform JS type judgment. It can only be used to judge complex data types, because instanceof is used to detect whether the prototype property of the constructor function (on the right) appears on the prototype chain of a certain instance object (on the left). For example:

    function Func() {}
    const func = new Func()
    console.log(func instanceof Func) // true
    
    const obj = {}
    const arr = []
    obj instanceof Object // true
    arr instanceof Object // true
    arr instanceof Array // true
    
    const str = "abc"
    const str2 = new String("abc")
    str instanceof String // false
    str2 instanceof String // true

Using instanceof alone doesn't seem to work, but we have concluded that typeof cannot distinguish between arrays and objects. So, let's combine instanceof to write a complete judgment logic.

    function myTypeof(data) {
        const type = typeof data
        if (data === null) {
            return 'null'
        }
        if (type !== 'object') {
            Return type
        }
        if (data instanceof Array) {
            return 'array'
        }
        return 'object'
    }

Object.prototype.toString.call()

Above we implemented a version of type judgment through typeof and instanceof, so are there other channels to make our code more concise? The answer is to use Object.prototype.toString.call().

Every object has a toString() method, which is called automatically when you want to represent the object as a text value or refer to the object in a way that expects a string. By default, every object derived from Object inherits the toString() method. If this method is not overridden in a custom object, toString() returns

    Object.prototype.toString.call(new Date()) // [object Date]
    Object.prototype.toString.call("1") // [object String]
    Object.prototype.toString.call(1) // [object Numer]
    Object.prototype.toString.call(undefined) // [object Undefined]
    Object.prototype.toString.call(null) // [object Null]

So based on the above knowledge points, we can encapsulate the following general type judgment method:

    function myTypeof(data) {
        var toString = Object.prototype.toString;
        var dataType = data instanceof Element ? "element" : toString.call(data).replace(/\[object\s(.+)\]/, "$1").toLowerCase()
        return dataType
    };

    myTypeof("a") // string
    myTypeof(1) // number
    myTypeof(window) // window
    myTypeof(document.querySelector("h1")) // element

constructor

The constructor judgment method is similar to instanceof, but the constructor detection of Object is different from instanceof. The constructor can also handle the detection of basic data types, not just object types.

Notice:

1.null and undefined have no constructor;

2. Use () when judging numbers, such as (123).constructor. If you write 123.constructor, you will get an error.

3. The constructor will fail when the class inherits because the Object is overwritten and the detection result is incorrect

    function A() {};
    function B() {};
    A.prototype = new B();
    console.log(A.constructor === B) // false

    var C = new A();
    console.log(C.constructor === B) // true
    console.log(C.constructor === A) // false 

    C.constructor = A;
    console.log(C.constructor === A); // true
    console.log(C.constructor === B); // false

Array.isArray()

Array.isArray() is used to determine whether the passed value is an Array. Returns true if the object is an Array<String, String>, otherwise false.

    Array.isArray([1, 2, 3]); // true
    Array.isArray({foo: 123}); // false
    Array.isArray("foobar"); // false
    Array.isArray(undefined); // false

Regular judgment

We can convert objects and arrays into a string, so that we can do format judgment and get the final type.

    function myTypeof(data) {
        const str = JSON.stringify(data)
        if (/^{.*}$/.test(data)) {
            return 'object'
        }
        if (/^\[.*\]$/.test(data)) {
            return 'array'
        }
    }

Summarize

This is the end of this article about the correct method to judge the data type in JS. For more relevant JS data type judgment 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!

This is the end of this article about the correct method to judge the data type in JS. For more relevant JS data type judgment 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:
  • 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
  • Four methods of using JS to determine data types
  • Four data type judgment methods in JS
  • Share several methods of JavaScript type judgment

<<:  MySQL 5.7 generated column usage example analysis

>>:  Install nvidia graphics driver under Ubuntu (simple installation method)

Recommend

MySQL 5.7.17 winx64 installation and configuration graphic tutorial

I summarized the previous notes on installing MyS...

js to realize a simple puzzle game

This article shares the specific code of js to im...

HTML web page creation tutorial Use iframe tags carefully

Using iframes can easily call pages from other we...

HTML tutorial, understanding the optgroup element

Select the category selection. After testing, IE ...

Summary of common problems and solutions in Vue (recommended)

There are some issues that are not limited to Vue...

The difference between key and index in MySQL

Let's look at the code first: ALTER TABLE rep...

The front-end must know how to lazy load images (three methods)

Table of contents 1. What is lazy loading? 2. Imp...

Detailed steps to upgrade mysql8.0.11 to mysql8.0.17 under win2008

Upgrade background: In order to solve the vulnera...

How to quickly modify the table structure of MySQL table

Quickly modify the table structure of a MySQL tab...

Dynamic SQL statement analysis in Mybatis

This article mainly introduces the dynamic SQL st...

How to view Linux ssh service information and running status

There are many articles about ssh server configur...

JavaScript implements single linked list process analysis

Preface: To store multiple elements, arrays are t...

How to make if judgment in js as smooth as silk

Table of contents Preface Code Implementation Ide...

MySQL and sqlyog installation tutorial with pictures and text

1. MySQL 1.1 MySQL installation mysql-5.5.27-winx...