Home Web Front-end JS Tutorial A brief introduction to four methods of data type detection in JS

A brief introduction to four methods of data type detection in JS

Aug 06, 2018 pm 05:09 PM

In JS, we can define all types of variables with only one var, which is very convenient, but it also causes us trouble. If we want to know what type the return value of a function is, or what the input information is When determining the type, we need to detect the data, so how do we detect the data type?

Data type detection method:

  • typeof: Operator used to detect data type

  • instanceof: Used to detect whether an instance belongs to a certain class

  • constructor: The constructor function is very similar to instanceof

  • Object.prototype.toString .call(); The most accurate and commonly used method

typeof
typeof: operator used to detect data type; the method of use is typeof detection Content.

Use typeof to detect data types. First, a string is returned, and the string contains the corresponding data type;

var num  = 2;
console.log(typeof num); // ->控制台输出字符串numberconsole.log(typeof typeof typeof typeof function () {}); 
 // 输出的结果为字符串String,因为第一次使用typeof检测后结果为一个字符串数据类型的数据,以后每次检测都是String
Copy after login

Limitations of typeof
1. The result of typeof null is "object"
2. It cannot be specifically broken down whether it is an array, a regular expression, or other values ​​in the object, because typeof is used to detect the data type. For the left and right values ​​​​in the object data type, the final returned result is "object"


instanceof
instanceof: used to detect whether an instance belongs to a certain class; usage method: instance instanceof class name

Limitations of instanceof
1. It cannot be used to process basic type values ​​created by literals: For basic data types, there is a certain difference between the results created by literals and the results created by instances. In a strict sense, only the result created by the instance is the value of the standard object data type, and it is also an instance of the standard Number class; the result created by the literal method is the basic data type value, not a strict instance. , but due to the looseness of JS, the method provided on Number.prototype can be used

 console.log(1 instanceof Number);//->控制台输出false
 console.log(new Number(1) instanceof Number);//-> 控制台输出true
Copy after login
  1. instanceof As long as it is on the prototype chain of the current instance, the results we detect are all true

  2. In the prototype chain inheritance of the class, the final result we detected may not be correct

 function Fn() {
 }  
 var  ary = new Array;
 Fn.prototype = ary;//原型继承:让子类的原型等于父类的一个实例
 var  f =new Fn; // f->Fn.prototype->Array.prototype->Object.prototype
 console.log(f instanceof Array); //-> true
Copy after login

constructor: constructor
constructor: constructor This method is very similar to instanceof

var obj = [];
console.log(obj.constructor === Array ); //->trueconsole.log(obj.constructor === RegExp); //->false//console还可以出来基本的数据类型var num = 1;
console.log(num.constructor === Number);//->true// constructor检测和instanceof一同,一般情况下是检测不了的var  reg = /^$/;
console.log(reg.constructor === RegExp);//-> trueconsole.log(reg.constructor === RegExp);//-> false
Copy after login

Limitations: We can rewrite the prototype of the class, and it is very easy to do so during the rewriting process It is possible that the previous constructor has been overwritten, so the detected results are inaccurate; for the special data types null and undefined, their classes are Null and Undefined, but the browser protects these two classes. We are not allowed to access using

function Fn() {}  
Fn.prototype = new Array;var  f =new Fn;
console.log(f.constructor);//-> Array
Copy after login

Object.prototype.toString.call()
This method is the one we have used the longest in our project and is now the most accurate. One way
First get the toString method on the Object prototype, let the method execute, and change the pointing of the this keyword in the method
Before understanding this method, let’s first understandtoString This method
toString: literally converts it into a string, but some toString methods do more than just convert it into a string; for Number, String, Boolean, Array The toString methods on the , RegExp, Date, and Function prototypes all ① convert the current data type into a string type (their function is only to convert into a string); but the toString method on the Object prototype is different from these , ② Its function is to return the detailed information of the class to which the execution body of the current method (this in the method) belongs.
The first type is converted to a string

        //Number.prototype.toString方法是转化为字符串  
        console.log((1).toString()); //->这里的toString是Number.prototype.toString用法是转成字符串-> '1'
        console.log((1).__proto__.__proto__.toString());//[object Object]
        console.log((128).toString(2/8/10));//把数字转化为二进制、八进制、十进制
Copy after login

#
 ({name:'编程'}).toString();
 console.log(obj.toString());//-> toString中的this是Obj,返回的是obj所属类的信息->[Object Object]第一个Object代表当前实例是对象数据类型的(这个是固定死的),第二个Object代表的是obj所属的类是ObjectMath.toString();//->toString中的this是Math,返回的是Math所属类的信息 ->  [Object Math]console.log(Object.prototype.toString.call([]));                //->[object Array]console.log(Object.prototype.toString.call(/^$/));               //->[object Array]console.log(({}).toString.call(new  Date));                      //->[object Date]console.log(Object.prototype.toString.call(1));                  //->[object Number]console.log(Object.prototype.toString.call('编程'));             //->[object String]console.log(Object.prototype.toString.call(null));               //->[object Null]console.log(Object.prototype.toString.call(undefined));          //->[object Undefined]console.log(Object.prototype.toString.call(function () {}));     //->[object Function]
Copy after login

all on the Object prototype after comparison with our fourth method The accuracy is the highest, so it is often used in our projects. Are you get it!!!

Related recommendations:

Detailed explanation of several ways to detect data types in javaScript Summary

js Several methods to determine data type

The above is the detailed content of A brief introduction to four methods of data type detection in JS. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do I create and publish my own JavaScript libraries? How do I create and publish my own JavaScript libraries? Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

How do I optimize JavaScript code for performance in the browser? How do I optimize JavaScript code for performance in the browser? Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

How do I debug JavaScript code effectively using browser developer tools? How do I debug JavaScript code effectively using browser developer tools? Mar 18, 2025 pm 03:16 PM

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How do I use source maps to debug minified JavaScript code? How do I use source maps to debug minified JavaScript code? Mar 18, 2025 pm 03:17 PM

The article explains how to use source maps to debug minified JavaScript by mapping it back to the original code. It discusses enabling source maps, setting breakpoints, and using tools like Chrome DevTools and Webpack.

Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts Mar 15, 2025 am 09:19 AM

This tutorial will explain how to create pie, ring, and bubble charts using Chart.js. Previously, we have learned four chart types of Chart.js: line chart and bar chart (tutorial 2), as well as radar chart and polar region chart (tutorial 3). Create pie and ring charts Pie charts and ring charts are ideal for showing the proportions of a whole that is divided into different parts. For example, a pie chart can be used to show the percentage of male lions, female lions and young lions in a safari, or the percentage of votes that different candidates receive in the election. Pie charts are only suitable for comparing single parameters or datasets. It should be noted that the pie chart cannot draw entities with zero value because the angle of the fan in the pie chart depends on the numerical size of the data point. This means any entity with zero proportion

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles