zoukankan      html  css  js  c++  java
  • js类型检测

    类型检测常用三种方法

    1. typeof
    2. instanceof
    3. Object.prototype.toString.apply()

    一、typeof

    适用于基本类型以及function检测,遇到null失效

    typeof 100 //number
    typeof true //boolean
    typeof function //function
    typeof undefined //undefined
    typeof new Object() //object
    typeof [1,2] //object
    typeof NaN //number
    typeof null //object
    

    二、instanceof

    适合自定义对象,也可用来检测原生对象,在不同的iframe以及window之间检测时失效

    [1,2]instanceof Array //true
    new Object() instanceof Array //false
    new Object() instanceof Object //true
    1 instanceof Number //false
    "string" instanceof String //false
    

    从上面代码也可以看出基本类型并不能通过instanceof检测

    三、Object.prototype.toString.apply()

    适合内置对象以及基元类型

    Object.prototype.toString.apply(1)
    "[object Number]"
    Object.prototype.toString.apply([1,2,3,4])
    "[object Array]"
    Object.prototype.toString.apply(new Object())
    "[object Object]"
    Object.prototype.toString.apply(function(){})
    "[object Function]"
    Object.prototype.toString.apply(null)
    "[object Null]"
    Object.prototype.toString.apply(true)
    "[object Boolean]"
    Object.prototype.toString.apply(undefined)
    "[object Undefined]"
    Object.prototype.toString.apply("string")
    "[object String]"
    

    这个方法检测类型很酷,是不是!!!

    注意:

    在IE678中Object.prototype.toString.apply(null)返回的仍是object

    其他两种判断方法

    自己百度去吧!!!

    1. constructor
    2. duck type
  • 相关阅读:
    如何查看ubuntu版本
    基于Python与命令行人脸识别项目(系列一)
    问题 B: Curriculum Vitae
    问题 M: 克隆玩具
    1906: 鹊桥相会
    3265: 聪明的矿工
    2363: 完美旗手队列
    2545: 内部收益率
    2544: 台球碰撞
    3272: 公民身份号码
  • 原文地址:https://www.cnblogs.com/zheng-chuang/p/6854235.html
Copyright © 2011-2022 走看看