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] 
  • 相关阅读:
    有继承的C++析构函数一定要用virtual
    CUDA vs2010配置
    lambda calculus(1)
    SICP练习1.6 1.16 解答
    用函数式来实现集合
    osx guile编译安装
    skiplist poj2892
    [转]理解 pkgconfig 工具
    专业术语解释
    【转】如何学习linux设备驱动
  • 原文地址:https://www.cnblogs.com/luguiqing/p/8655115.html
Copyright © 2011-2022 走看看