当前位置: 移动技术网 > IT编程>开发语言>Java > toString.call()通用的判断数据类型方法示例

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

2020年08月29日  | 移动技术网IT编程  | 我要评论
大家都知道判断数据类型的方法有很多。我们常用的有typeof但是,这个方法有一定的局限性。typeof null// "object" typeof [8]// "object" typeof {}/

大家都知道判断数据类型的方法有很多。我们常用的有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()判断数据类型内容请搜索移动技术网以前的文章或继续浏览下面的相关文章希望大家以后多多支持移动技术网!

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网