Summary of Several Ways to Detect Data Types in javaScript

  • 2021-07-26 06:19:32
  • OfStack

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? The code circulating on the Internet is everywhere, but it is found that some of them are wrong, so I simply used each method once by myself. Today, I specially sorted it out for future reference.

1. typeof detection

typeof is a 1-element operator, syntax: typeof (operand), operand can be any type. Its return value is a string that describes the type of operand.


// var arr = { name:"john"}; // object
  // var arr = [" Language "," Mathematics "]; // object
  // function Person() {};  // typeof(Person) => function
  // var arr = ' I am a string ' ; // 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 an object is an instance of another object, which can be used in inheritance relationship to determine whether an instance belongs to its parent type.


// var arr = ' I am a string ' ;       // 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 = [" Language "," Mathematics "];     // 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 as follows: Object. prototype. toString. call (value)


// var arr = ' I am a string ' ;   //[object String]
    // var arr = 66 ;        //[object Number]
    // var arr = true ;       //[object Boolean]
    // var arr = [" Language "," Mathematics "];  //[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) );


Related articles: