Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

js检查复杂数据类型 #295

Open
aaaaaajie opened this issue Nov 13, 2019 · 2 comments
Open

js检查复杂数据类型 #295

aaaaaajie opened this issue Nov 13, 2019 · 2 comments

Comments

@aaaaaajie
Copy link

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]
  }
}
@lzq920
Copy link

lzq920 commented Nov 14, 2019

复杂类型应该还包含有Regexp,Math这些吧??

@aaaaaajie
Copy link
Author

@lzq920 是的,没有拓展那么全,只提到了一些常用的工具

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants