zoukankan      html  css  js  c++  java
  • 使用Object对象的toString()方法自定义判断数据类型方法

    Object.prototype.toString方法返回对象的类型字符串

    Object.prototype.toString.call(2)     //  "[object Number]"
    Object.prototype.toString.call("")    // "[object String]"
    Object.prototype.toString.call(true)  // "[object Boolean]"
    Object.prototype.toString.call(undefined)     //  "[object Undefined]"
    Object.prototype.toString.call(null)    // "[object Null]"
    Object.prototype.toString.call(Math)  // "[object Math]"
    Object.prototype.toString.call({})     //  "[object Object]"
    Object.prototype.toString.call([])    // "[object Array]"
    

    利用以上特性,可以构造一个比typeof运算符更准确的类型判断函数

    var dataType = function(o){
        var s = Object.prototype.toString.call(o);
        return s.match(/[object (.*?)]/)[1].toLowerCase();
    }
    
    dataType([]);  //  "array"
    

    专门判断某一个类型

    ['Null', 'Undefined', 'Object', 'Array', 'String', 'Number', 'Boolean', 'Function', 'RegExp', 'NaN', 'Infinite'].forEach(function(item){
        dataType['is' + item] = function(o){
            return dataType(o) === item.toLowerCase();
        }
    })
    
    dataType.isObject({}) // true
    
  • 相关阅读:
    maven工程的目录结构
    集合的区别
    名词解析
    1.(字符串)-判断字符串是否是子集字符串
    1.(字符串)-判断两字符串是否相等
    python max函数技巧
    1.(字符串)-子字符串位置查找
    numpy线性代数np.linalg
    Python图像库PIL 使用
    pyhthon-chr
  • 原文地址:https://www.cnblogs.com/stone-it/p/7326946.html
Copyright © 2011-2022 走看看