JS에서 데이터 유형을 판단하는 방법
데이터 유형 을 판단하기 위한 JS 메서드의 완전한 물결을 공유 한 Xiaoroubao의 이전 블로그를 기반으로 보다 포괄적 인 방법을 공유하겠습니다. 이전 공유 콘텐츠와 다른 점은이 기사에서는 메서드를 선언해야합니다. 여러 데이터 유형을 판단하는 데 사용됩니다.
코드 쇼 :
/**
* 判断某个数据是否为某种类型
* 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
친구들에게 도움을 드리고 싶습니다! 내 개인 블로그 송동 장에 오신 것을 환영합니다