首页 > 编程技术 > js

toString.call()通用的判断数据类型方法示例

发布时间:2020-8-29 10:12

大家都知道判断数据类型的方法有很多。我们常用的有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)
// "symbol"

typeof 无法区分null 数组和对象,通常我们会区分判断Array和Object

有时会用instanceof 来判断是不是一个对象的实例子

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

下面介绍一种方法,对每一种数据类型都实用。

toString.call(function(){})
// "[object Function]"
 
toString.call(null)
//"[object Null]"
 
toString.call([2])
"[object Array]"
 
toString.call(undefined)
//"[object Undefined]"
 
toString.call('stjd')
//"[object String]"
 
toString.call(1)
//"[object Number]"
 
toString.call(true)
//"[object Boolean]"
 
toString.call(Symbol(3))
// "[object Symbol]"
 
toString.call({q:8})
//"[object Object]"

再来思考, toString.call([2]) 意思就是改变方法中的this指向,指向传递进去的参数,也就是[2]。那我这样写不是更直观吗?[2].toString()。结果

[2].toString()
//"2"

  var obj = {a: 67}
  console.log(obj.toString())
  // [object Array]

对比上面两个返回的值是不一样的。这是因为[2].toString()调用的是数组的toSting()方法,而不是对象的toSting()方法。Array改写了Object的toString方法。

toSting.call()实际上就是 Object.prototype.toSting.call()

console.log(Object.prototype.toString.call([33])) // [object Array]

而[2].toSting()实际上是

console.log(Array.prototype.toString.call([2])) //2

使用的过程中,可以这样封装函数

  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()通用的判断数据类型方法的文章就介绍到这了,更多相关toString.call()判断数据类型内容请搜索猪先飞以前的文章或继续浏览下面的相关文章希望大家以后多多支持猪先飞!

标签:[!--infotagslink--]

您可能感兴趣的文章: