首页 > Web开发 > 详细

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

时间:2019-01-28 23:31:09      阅读:150      评论:0      收藏:0      [点我收藏+]

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

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

原文:https://www.cnblogs.com/ye-hcj/p/10332162.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!