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

总结

华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com

RTX 5090要首发 性能要翻倍!三星展示GDDR7显存

三星在GTC上展示了专为下一代游戏GPU设计的GDDR7内存。

首次推出的GDDR7内存模块密度为16GB,每个模块容量为2GB。其速度预设为32 Gbps(PAM3),但也可以降至28 Gbps,以提高产量和初始阶段的整体性能和成本效益。

据三星表示,GDDR7内存的能效将提高20%,同时工作电压仅为1.1V,低于标准的1.2V。通过采用更新的封装材料和优化的电路设计,使得在高速运行时的发热量降低,GDDR7的热阻比GDDR6降低了70%。