美文网首页前端
toString.call()来检测数据类型

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

作者: 若年 | 来源:发表于2021-04-25 15:08 被阅读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")

相关文章

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

    最近在读elementUI源码的时候发现了这样一段代码 其中用toString.call()来检测数据类型,这样的...

  • JS-NO.3

    数据类型检测 4种方式 1:typeof 主要检测基本数据类型 不能具体检测出引用数据类型 2:constru...

  • 20170710笔记

    数据类型检测有4种方法 type of 主要用于基本数据类型检测,不能具体检测出引用数据类型 constructo...

  • 2019-03-19 js practice three

    数据类型检测有4种方法 typeof 主要用来检测基本数据类型,不能具体检测出引用数据类型 constructor...

  • {}.toString.call(obj)判断数据类型

    先看一下typeof 按照上面的打印结果,总结出以下几点:1 除了函数 function,typeof ‘引用类...

  • Object.prototype.toString.call检测

    1. 为什么可以检测数据类型 我们知道typeof可以检测数据类型,但是是不准确的,比如 想更准备的检测数据类型可...

  • js笔记五十之数据类型检测

    数据类型检测 typeof 用来检测数据类型的运算符 使用typeof检测数据类型, 首先返回的都是一个字符串其次...

  • 数据类型检测

    数据类型检测

  • Js类型相关总结

    Js的基本数据类型 复杂数据类型 类型检测 typeof 检测检测原理是根据变量存储时低位 instanceof检...

  • javascript面试题

    数据类型 1.有哪几种数据类型 2.说说基本数据类型和引用数据类型的不同 3.如何检测数据类型 4.如何检测对象,...

网友评论

    本文标题:toString.call()来检测数据类型

    本文链接:https://www.haomeiwen.com/subject/ramdrltx.html