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

    几种方法:typeof,instanceof,Object.prototype.toString,constructor,duck type

    ES6引入了一种新的原始数据类型Symbol,表示独一无二的值。它是JavaScript语言的第七种数据类型,前六种是:Undefined、Null、布尔值(Boolean)、字符串(String)、数值(Number)、对象(Object)。

    JavaScript5种基本类型:undefined,Number,String,null,boolean

    js是一种宽松类型语言;


    特殊的数值:Infinity、NaN(与自己都不相等)、Number.MAX_VALUE、Number.POSITIVE_INFINITY、

    typeof返回值:

    function,object,boolean,string,number,undefined;

    对null使用typeof返回的是"object" 

     

    数据类型

    转化成true的值

    转化成false的值

    Boolean          

    ture

    false

    String    

    所有的非空字符串                

    ""(空字符串)

    Number

    任何非零数字(包括无穷大)            

    0和NaN                                    

    Object

    任何对象

    不存在

    Undefined          

    不存在

    undefined

     确定对象类型:typeof 不是object就是类型,否则tostring()方法返回值,但这样还是不能判断自定义类;

    1)typeof:

    function isUndefined(value){return typeof value == 'undefined';}

    function isDefined(value){return typeof value != 'undefined';}

    function isObject(value){return value != null && typeof value == 'object';}

    function isString(value){return typeof value == 'string';}

    function isNumber(value){return typeof value == 'number';}

    function isFunction(value){return typeof value == 'function';}

    function isBoolean(value) {

      return typeof value == 'boolean';

    }

    2)toString:

    function isDate(value){

      return toString.apply(value) == '[object Date]';

    }

    function isArray(value) {

      return toString.apply(value) == '[object Array]';

    }

    function isFile(obj) {

      return toString.apply(obj) === '[object File]';

    }

    3)(duck type)判断是否有某属性或方法:

    function isWindow(obj) {

      return obj && obj.document && obj.location && obj.alert && obj.setInterval;

    }

    function isScope(obj) {

      return obj && obj.$evalAsync && obj.$watch;

    }

    function isElement(node) {

      return node &&

        (node.nodeName  // we are a direct element

        || (node.bind && node.find));  // we have a bind and find method part of jQuery API

    }

    instanceof  

  • 相关阅读:
    发现IDEA两个超级好用的工具
    事务的传播属性
    Java 单元测试PowerMockito
    Spirng源码学习 第一天
    2021年 每日打卡
    Spring源码调试环境搭建成功
    practice
    学习进度表
    报数
    负二进制转换
  • 原文地址:https://www.cnblogs.com/zqiong/p/6181009.html
Copyright © 2011-2022 走看看