Skip to content

js检查复杂数据类型 #295

@aaaaaajie

Description

@aaaaaajie

typeof 只能判断基本数据类型,复杂类型看下面

1.构造函数

const arr = [1, 2, 3]
arr.constructor === Array // true
arr.constructor === Object // false
arr.constructor // [Function: Array]

其他以此类推。

2.原型方式

const arr = [1,2,3]
const type = Object.prototype.toString.call(arr)
type === '[object Array]' // true

其他以此类推。

以下给两个工具类,视情况选择

工具一:==返回值是布尔类型==

/* 类型检查 返回 true/flase */
 对应方式一
class jsType {
  static isArray(value) {
    return value.constructor === Array
  }

  static isObject(value) {
    return value.constructor === Object
  }

  static isUndefined(value) {
    return value === undefined
  }

  static isString(value) {
    return value.constructor === String
  }

  static isNull(value) {
    return value === null
  }

  static isFunction(value) {
    return value.constructor === Function
  }

  static isNumber(value) {
    return value.constructor === Number
  }

  static isBoolean(value) {
    return value.constructor === Boolean
  }
}
// 测试示例
jsType.isArray([1, 2, 3])
jsType.isNumber(1)
jsType.isString('字符串')
jsType.isBoolean(true)
jsType.isObject({ name: 'ipenman', age: 12 })
jsType.isFunction(function() {})
jsType.isNull(null)
jsType.isUndefined(undefined)

工具二:==返回值是该对象的数据类型==

/* 类型检查 返回 true/flase */
function jsType(value) {
  const oType = {
    '[object Array]': 'Array',
    '[object Object]': 'Object',
    '[object Number]': 'Number',
    '[object String]': 'String',
    '[object Boolean]': 'Boolean',
    '[object Undefined]': 'undefined',
    '[object Null]': 'null',
    '[object Function]': 'Function',
    '[object Date]':'Date'
  }
  const sType = Object.prototype.toString.call(value)
  for (const item in oType) {
    if (sType === item) return oType[item]
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions