Home > Web Front-end > JS Tutorial > body text

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

php是最好的语言
Release: 2018-08-06 17:09:06
Original
1532 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!