zoukankan      html  css  js  c++  java
  • js之精确的区分数据类型

    1. typeof

    主要用于判断数据是不是基本数据类型:string、number、object、undefined、boolean,但是无法判断出function(有些浏览器会出错)、array、regExp、null

    console.log(typeof '');//string  
    console.log(typeof []);//object  
    console.log(typeof {});//object  
    console.log(typeof 1);//number  
    console.log(typeof null);//object  
    console.log(typeof undefined);//undefined  
    console.log(typeof true);//boolean  
    console.log(typeof function(){});//function  
    console.log(typeof /d/);//object  

    2. instanceof

    主要的目的是用来检测引用类型,判断Array和RegExp,无法准确判断Function

    console.log([] instanceof Array);//true  
    console.log({} instanceof Object);//true  
    console.log(/d/ instanceof RegExp);//true  
    console.log(function(){} instanceof Object);//true  
    console.log(function(){} instanceof Function);//true  
    
    console.log('' instanceof String);//false  
    console.log(1 instanceof Number);//false

    3. Object.prototype.toString

    对象的一个原生原型扩展函数,用来精确的区分数据类型

    Object.prototype.toString.call(data).slice(8,-1) === 'Array'
    
    var type=Object.prototype.toString;  
    console.log(type.call(''));//[object String]
    console.log(type.call([]));//[object Array]  
    console.log(type.call({}));//[object Object]  
    console.log(type.call(false));//[object Boolean]  
    console.log(type.call(null));//[object Null]  
    console.log(type.call(undefined));//[object Undefined]  
    console.log(type.call(function(){}));//[object Function] 
  • 相关阅读:
    SSM框架--详细整合教程
    ssh--整合注意事项
    SSH--三大框架整合原理
    springMVC的流程
    java框架问题整理
    集合的体系
    java异常机制
    java知识点
    Java编程思想【Thinking in java】
    实验三 指令实验(一)
  • 原文地址:https://www.cnblogs.com/luguiqing/p/8655115.html
Copyright © 2011-2022 走看看