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

最近在读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")
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容