今天就跟大家聊聊有关使用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)
// "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()如何实现判断数据类型有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。