JavaScript判断各种数据类型

  • typeof ,只可判断部分数据的数据类型

    • 数字
    • 字符串
    • 布尔值
    • undefined
    • function
  • Object.prototype.toString.call()

  • instanceof

function judgeType(data) {
    // 不传参,默认undefined
    if (data === undefined) { return "undefined" }
    if (data === null) { return "null" }
    
    const type = Object.prototype.toString.call(data)
    return type.match(/^\[object (\w+)\]$/)[1]
}

judgeType(1)     // Number
judgeType('abc') // String
judgeType(true)  // Boolean
judgeType(undefined) // Undefined
judgeType(null)  // Null
judgeType({})   // Object
judgeType([])   // Array
judgeType(window)   // "Window"
posted @ 2019-03-26 17:02  _Jarrett  阅读(291)  评论(0编辑  收藏  举报