Method of judging data type in JS
On the basis of Xiaoroubao’s previous blog sharing a complete wave of JS methods for judging data types , I will share a more comprehensive method. The difference from the previous sharing content is that in this article, only Need to declare a method, it can be used to judge multiple data types.
code show as below:
/**
* 判断某个数据是否为某种类型
* by 小肉包
* @params type 想要判断的类型
* @params value 想要判断的数据
* 返回值 :布尔值(true / false)
*/
function belongTo(type, value) {
switch (type) {
case Number:
{
return Object.prototype.toString.call(value) === '[object Number]'
}
case Boolean:
{
return Object.prototype.toString.call(value) === '[object Boolean]'
}
case String:
{
return Object.prototype.toString.call(value) === '[object String]'
}
case Array:
{
return Object.prototype.toString.call(value) === '[object Array]'
}
case Object:
{
return Object.prototype.toString.call(value) === '[object Object]'
}
case Function:
{
return Object.prototype.toString.call(value) === '[object Function]'
}
case null:
{
return Object.prototype.toString.call(value) === '[object Null]'
}
case undefined:
{
return Object.prototype.toString.call(value) === '[object Undefined]'
}
case Date:
{
return Object.prototype.toString.call(value) === '[object Date]'
}
default:
{
return false;
}
}
}
//使用举例:
console.log( belongTo(Number, 52) ) // true
console.log( belongTo(String, '这是字符串吗') ) // true
let arr = [1,5,12]
let a=500
console.log( belongTo(Array, arr) ) // true
console.log( belongTo(String, a) ) // false
Hope to bring help to my friends! Welcome to my personal blog songdong chapter