In the process of programming with javaScript, we often encounter such a problem, that is, we need to detect the type of a data or variable, this article This article mainly introduces a summary of several ways to detect data type in javaScript. Those who are interested can learn more.
In the process of programming with javaScript, we often encounter such a problem, that is, we need to detect the type of a data or variable. So what methods are provided for us in javaScript? There are a lot of codes circulating on the Internet, but I found that some of them were wrong, so I simply used each method myself. Today I specially sorted it out for future reference.
1. Typeof detection
typeof is a unary operator, syntax: typeof (operand), the operand can be of any type. Its return value is a string that describes the type of the operand.
// var arr = { name:"john"}; // object // var arr = ["语文","数学"]; // object // function Person() {}; // typeof(Person) => function // var arr = '我是字符串' ; // string // var arr = 66 ; // number // var arr = true ; // boolean // var arr = new Person(); // object // var arr = undefined; // undefined // var arr = null; // object // var arr = /^\d{5,20}$/; // object // console.log( typeof(arr) );
2. instanceof detection
instanceof detects whether a object is an instance of another object , can be used in the inheritance relationship to determine whether an instance belongs to its parent type.
// var arr = '我是字符串' ; // console.log( arr instanceof String ) => false // var arr = 66 ; // console.log( arr instanceof Number ) =>false // var arr = true ; // console.log( arr instanceof Boolean ) =>false // var arr = ["语文","数学"]; // console.log( arr instanceof Array ) =>true // var arr = { name:"john"}; // console.log( arr instanceof Object ) =>true // var arr = function Person(){}; //console.log(arr instanceof Function)=>true // var arr = undefined; // console.log(arr instanceof Object)=>false // var arr = null; // console.log(arr instanceof Object)=>false // var arr = /^\d{5,20}$/; // console.log(arr instanceof RegExp)=>true
3. Object.prototype.toString.call detection
Use the native toString() method on Object.prototype to determine the data type. The usage method is as follows: Object.prototype.toString.call(value)
// var arr = '我是字符串' ; //[object String] // var arr = 66 ; //[object Number] // var arr = true ; //[object Boolean] // var arr = ["语文","数学"]; //[object Array] // var arr = { name:"john"}; //[object Object] // var arr = function Person(){}; //[object Function] // var arr = undefined; //[object Undefined] // var arr = null; //[object Null] // var arr = /^\d{5,20}$/; //[object RegExp] // console.log( Object.prototype.toString.call(arr) );
The above is the detailed content of Detailed explanation of several ways to detect data types in JavaScript. For more information, please follow other related articles on the PHP Chinese website!