zoukankan      html  css  js  c++  java
  • JavaScript判断变量的类型

    1. 通过typeof来判断

    2. 通过instanceof来判断 或 通过constructor来判断

    3. null直接全等判断即可

    4. 万能判断方式:Object.prototype.toString.call()

    1. 通过typeof来判断

    typeof undefined // undefined 
    typeof 1 // number 
    typeof '1' // string 
    typeof true // boolean 
    typeof function() {} // function 
    typeof Symbol() // symbol
     
    // 以下类型需要别的方式判断
    typeof null // object 
    typeof {} // object 
    typeof [] // object

    2. 通过instanceof来判断 或 通过constructor来判断

    // 以下这个不准确,因为instanceof会去找原型链。而引用类型的__proto__最终都会指向Object.prototype。
    obj instanceof Object // true
    [] instanceof Object // true
    new Date() instanceof Object // true
    new RegExp() instanceof Object // true
    
    // 判断对象更好的方式:
    obj.constructor === Object // true
    
    // 判断数组
    [] instanceof Array // true
    [].constructor === Array // true
    
    // 判断日期对象
    new Date() instanceof Date // true
    new Date().constructor === Date // true
    
    // 判断正则表达式对象
    new RegExp() instanceof RegExp // true
    new RegExp().constructor === RegExp // true

    3. null直接全等判断即可

    null === null // true

    4. 万能判断方式:Object.prototype.toString.call()

    // 引用类型
    Object.prototype.toString.call({}) // [object Object]
    Object.prototype.toString.call([]) // [object Array]
    Object.prototype.toString.call(new Date()) // [object Date]
    Object.prototype.toString.call(new RegExp()) // [object RegExp]
    Object.prototype.toString.call(function(){}) // [object Function]
    
    // 基本类型
    Object.prototype.toString.call(null) // [object Null]
    Object.prototype.toString.call(undefined) // [object Undefined]
    Object.prototype.toString.call(true) // [object Boolean]
    Object.prototype.toString.call('1') // [object String]
    Object.prototype.toString.call(1) // [object Number]
    Object.prototype.toString.call(Symbol()) // [object Symbol]
  • 相关阅读:
    Goland在go mod vendor模式下无法识别某些库
    国际教育游戏实证研究综述:2008年-2012年
    ES6之用let,const和用var来声明变量的区别
    集成spring boot + mysql + docker实战
    js sort方法根据数组中对象的某一个属性值进行排序(实用方法)
    小试牛刀之sort()排序的实现
    Redis字符串(STRING)中BIT相关命令
    koa,express,node 通用方法连接MySQL
    JavaScript预解释是一种毫无节操的机制
    [php]如何做到高并发优化
  • 原文地址:https://www.cnblogs.com/hiuman/p/14178651.html
Copyright © 2011-2022 走看看