js是这样判断值的数据类型的

js如何判定给定值的数据类型?

  1. typeof

    typeof "a"              // "string"
    typeof 1                // "number"
    typeof true             // "boolean"
    typeof {}               // "object"
    typeof []               // "object"
    typeof null             // "object"
    typeof function(){}     // "function"
    typeof a                // "undefined"
  2. 终极判断

    注意到上面的typeof在使用的时候有很多object
    Object.prototype.toString.call({})      // "[object Object]"
    Object.prototype.toString.call([])      // "[object Array]"
    Object.prototype.toString.call(null)    // "[object Null]"
  3. 判断实例从属哪个类

    instanceof关键字可以判定一个引用类型值是否继承自其他类或者是其他类的实例
    instanceof关键字对任何值类型使用都是无意义的
    注意如下区别
    [] instanceof Array             // true
    [] instanceof Object            // true
    [].constructor === Array        // true
    [].constructor === Object       // false

猜你喜欢

转载自www.cnblogs.com/ye-hcj/p/10332162.html