• javascript类型判断


    通常为了快捷我们都会使用 typeof 操作符去判断变量的类型,但是这种做法不能准确判断出变量的类型。

    比如:

    typeof [];    // 返回 'object'
    typeof {};    // 返回 'object'
    typeof new Number(1);    // 返回 'object'
    typeof new Array('a', 'b');    // 返回 'object'
    typeof new String('abc');  
    // 返回 'object'
    typeof new Function();  // 返回 'function'

    typeof 操作符在判断 new 出来的对象时除了 new Function 其他通常返回 'object'。

    因此为了能准确判断类型,我们找到了一个更好的方法就是通过 call 调用 Object 原型上的 toString 方法来获取变量的具体类型。

    Object.prototype.toString.call( obj );

    我看了下jquery里面的用来判断变量类型的 type 函数,实现得相对复杂。

    其用法类似是这样的:

    var abc = 'abc';
    if( jQuery.type( abc ) === 'string' ) {
        //是字符类型的话就执行这里
    }else{
        //不是就执行这里
    }

    jQuery.type 函数最终返回传进去变量的类型,还需要我们通过运算符比较来判断。

    觉得有些多余,不如像下面这样来的方便快捷:

    var abc = 'abc';
    if( isType(abc, 'string') ) {
        //true
    }else{
        //false
    }

    isType 函数接受一个字符串参数,直接返回 true 还是 false。

    我是这样实现的:

    function isType( obj, type ) {
        var toStr = Object.prototype.toString;
        var toLower = toStr.call( obj ).toLowerCase();
        return toLower.indexOf( '[object ' + type + ']' ) !== -1;
    }

    还有一个通过正则来实现的版本:

    function isType( obj, type ) {
        var toStr = Object.prototype.toString.call( obj );
        return (new RegExp('\[object ' + type + '\]' , "i")).test( toStr );
    }

    在javascript里类型判断非常常用,于是我把这个函数直接添加到 Object.prototype 上,这样的话每个变量都能继承这个函数了。

    Object.prototype.isType = function( type ) {
        var toStr = Object.prototype.toString;
        var toLower = toStr.call( this ).toLowerCase();
        return toLower.indexOf( '[object ' + type + ']' ) !== -1;
    };

    这样加上去的话就方便多了:

    'abc'.isType( 'string' )    // 返回true
    'abc'.isType( 'number' )    // 返回false
    
    ['a', 'b', 'c'].isType( 'array' )    // 返回true
    ['a', 'b', 'c'].isType( 'string' )    // 返回false
    
    (123).isType( 'number' )    // 返回true
    (123).isType( 'string' )    // 返回false
    
    new Date().isType( 'date' )    // 返回true
    new Date().isType( 'number' )    // 返回false
  • 相关阅读:
    2018,10,19模拟赛
    培训期间做题整理(部分)
    纪中2018暑假培训day5提高b组改题记录
    纪中2018暑假培训day7提高b组改题记录
    纪中2018暑假培训day3提高a组改题记录(混有部分b组)
    纪中2018暑假培训day1提高b组改题记录
    python中的‘/’和'//'
    对于python中的join函数和+
    python中的casefold函数和lower()函数区别
    F
  • 原文地址:https://www.cnblogs.com/ruleblog/p/4521288.html
Copyright © 2020-2023  润新知