47. Four ways of data type detection

1.typeof operator used to detect data type

  console.log(typeof 12);

  var num = "zhangsan";

  console.log(typeof num);

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

  例如:"number","string","boolean","undefined","function","object"

    console.log(typeof typeof typeof function(){}) // "string"

    console.log(typeof function(){}) // "function"

  limitation:

    a)console.log(typeof null) ->"object"

    b) It is impossible to subdivide whether it is an array or a regular, 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 result returned is "object"

    function fn(num1,num2) {

      if (typeof unm2 === "undefined") {

        num2 = 0

      }

    }

    fn(10)

    function fn1(callback) {

      typeof callback === "function" ? callback() : null

    }

    fn1(function() {})

2.instanceof detects whether an instance belongs to a certain class

  var obj = [12,23]

  console.log(obj instanceof Array);

  console.log(obj instanceof RegExp);

  limitation:

    1. Cannot be used to detect and process values ​​of primitive data types created by literals

    For basic data types, the result created by the literal method is different from the result created by the instance. Strictly speaking, only the result created by the instance is the standard object data type value, which is also the standard value. An instance of the Number class; the result created by the literal method is a basic data type value, not a strict instance, but due to the looseness of JS, the methods provided on the Number prototype can be used;

    console.log(1 instanceof Number); // false

    console.log(new Number(1) instanceof Number); // true

    console.log(true instanceof Boolean); // false

    2.

    var and = [];

    console.log(ary instanceof Array);// -true

    console.log(ary instanceof Object); // -true

    function fn() {}

    console.log(fn instanceof Function); // true

    console.log(fn instanceof Object); // true

3.constructor constructor

 

4.Object.prototype.toString.call()

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325212790&siteId=291194637
Recommended