JavaScript 类型判断

来源:互联网 发布:淘宝网不锈钢药磨 编辑:程序博客网 时间:2024/06/05 05:34

1.typeof

可作为 区分大的不同类型
可区分 类型: 字符串 、对象、布尔、function 、number、undefined
不能区分 : 对象里的详细类型; 例如 对象里的 数组、null 等等 (写在 3 内容里了)
特殊区分:能区分’undefined’,不能区分null(null是object) ===> typeof xxx

Value               Class      Type -- ------------------------------------------"foo"               String     stringnew String("foo")   String     object1.2                 Number     numbernew Number(1.2)     Number     objecttrue                Boolean    booleannew Boolean(true)   Boolean    objectnew Date()          Date       objectnew Error()         Error      object[1,2,3]             Array      objectnew Array(1, 2, 3)  Array      objectnew Function("")    Function   function/abc/g              RegExp     object (function in Nitro/V8)new RegExp("meow")  RegExp     object (function in Nitro/V8){}                  Object     objectnew Object()        Object     object

2. instanceof

只能原型链是构造函数的数据,否则判断不出来,例如:

null instanceof Object  // false,

可判断 元素 是否为 数组:

[] instanceof Array //  true 

3.Object.prototype.toString.call(xx) // [Object xx]

参考文章:https://bonsaiden.github.io/JavaScript-Garden/zh/#types.typeof

只检测 对象里的具体类型 ======== 补充 typoof 的判断

Object.prototype.toString.call([])  //  "[object Array]"Object.prototype.toString.call( null )  // "[object Null]"

结合正则,判断是不是某种类型

 /Object/.test(Object.prototype.toString.call({})) /Array/.test(Object.prototype.toString.call([])) /Function/.test(Object.prototype.toString.call(function(){})) /String/.test(Object.prototype.toString.call('abc'))

由此扩展:

写一个综合的类型判断:

function types(typeData){    if(typeof typeData !== 'object' ){        // return `${typeData} is not 'object' type`        return typeof typeData    }    _typeObj = Object.prototype.toString.call(typeData)    return _typeObj.split(']').length > 1 ? _typeObj.split(']')[0].split(' ').length > 0 ? _typeObj.split(']')[0].split(' ')[1] : 'Object.prototype.toString.call 过滤类型的字符串有异常' : '不在 typeof 与 toString 类型判断范围内'}
原创粉丝点击