javascript 开发中常用的类型比对

1. typeof 和 instanceOf

判断基本类型,用 typeof
判断复杂类型, 用 instanceof

instanceOf需要注意的是: instanceof在判断基本类型时,不是用 new 声明的类型会判断为false
如: 4 instanceOf Number 结果是false 但是 new Number(1) instanceOf Number 结果则为true
解决办法: 通过判断构造函数来解决上面这个问题
如: 4.constrructor === Number 结果为 true
注意的是上面这个解决办法对于 undefined 和 null 无效, 要解决这个问题可以使用下面介绍的 toString 方式。

另外使用 isArray 判断一个数组是否为数组时,要注意类型化数组会返回false,
具体见:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Typed_arrays

2.使用 toString() 检测对象类型(开发中常用):

let Type = (function () {
        let type = {};
        let typeArr = ['String', 'Object', 'Number', 'Array', 'Undefined', 'Function', 'Null', 'Symbol', 'Boolean', 'RegExp', 'BigInt'];
        for (let i = 0; i < typeArr.length; i++) {
            (function (name) {
                type['is' + name] = function (obj) {
                    return Object.prototype.toString.call(obj) === '[object ' + name + ']'
                }
            })(typeArr[i])
        }
        return type
    })()
    let s = true
    console.log(Type.isBoolean(s)) // true
    console.log(Type.isRegExp(/22/)) // true

除了能检测ECMAScript规定的八种数据类型(七种原始类型,Boolean,Null,Undefined,Number,BigInt,String,Symbol,一种复合类型Object)之外,还能检测出正则表达式RegExp,Function这两种类型,基本上能满足开发中的判断数据类型需求。

// 缺点就是NAN被检测为了一个数字, 可以用全局函数 isNaN 来替换判断 NaN 类型
console.log(Object.prototype.toString.call(NaN)) //[object Number]

3.Object.is() 方法判断两个值是否为同一个值。


另外== 和 === 相等运算符也是常用来判断值是否相等的一个方法,Object.is 是为了解决这运算符的一些缺点诞生的,详情见如下

参考文档:

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/is
toString() 方法返回一个表示该对象的字符串
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/toString
判断类型文章
https://www.cnblogs.com/tylerdonet/p/11852391.html

posted @ 2020-09-01 15:03  StackOcean  阅读(158)  评论(0编辑  收藏  举报