前端

toString.call()来检测数据类型

2021-04-25  本文已影响0人  若年

最近在读elementUI源码的时候发现了这样一段代码

 isChecked() {
        if ({}.toString.call(this.model) === '[object Boolean]') {
          return this.model;
        } else if (Array.isArray(this.model)) {
          return this.model.indexOf(this.label) > -1;
        } else if (this.model !== null && this.model !== undefined) {
          return this.model === this.trueLabel;
        }
      },

其中用toString.call()来检测数据类型,这样的方式无疑是比typeOf严谨的,特此记录一下。


typeof null
// "object"
 
typeof [8]
// "object"
 
typeof {}
// "object"
 
typeof function(){}
// "function"
typeof 2
//"number"
 
typeof ""
//"string"
 
typeof true
//"boolean"
 
typeof undefined
//"undefined"
 
typeof Symbol(2)

typeof 无法区分null 数组和对象.

再看一下instanceof

[] instanceof Array
 // true 这种方法可以判断数组,不能区分对象
[] instanceof Object
// true
 
null instanceof Object
// false 也不能区分null

再看看{}.toString.call()

console.log({}.toString.call(1))//[object Number]
console.log({}.toString.call("11"))//[object String]
console.log({}.toString.call(/123/))//[object RegExp]
console.log({}.toString.call({}))//[object Object]
console.log({}.toString.call(function(){}))//[object Function]
console.log({}.toString.call([]))//[object Array]
console.log({}.toString.call(true))//[object Boolean]
console.log({}.toString.call(new Date()))//[object Date]
console.log({}.toString.call(new Error()))//[object Error]
console.log({}.toString.call(null))//[object Null]
console.log({}.toString.call(undefined))//[object Undefined]
console.log(String(undefined))//undefined
console.log(String(null))//null

稍微封装一下

  function isType(type) {
      return function(obj) {
        return {}.toString.call(obj) == "[object " + type + "]"
      }
    }
    
    var isObject = isType("Object")
    var isString = isType("String")
    var isArray = Array.isArray || isType("Array")
    var isFunction = isType("Function")
    var isUndefined = isType("Undefined")
上一篇下一篇

猜你喜欢

热点阅读