js判断数据类型的函数

文章发布于 2023-05-01

js数据类型

js 拥有以下几种数据类型。分为基本类型和引用类型。基本类型是存在在栈中,每创建一个变量,就在栈中增加一个空间来存储变量的值,按值访问。引用类型存储在堆中,变量指向的一个堆的内存地址。

了解数据类型

基本数据类型:

  • number 数字
  • string 字符串
  • boolean 布尔
  • null 空
  • undefined 未定义
  • Symbol

引用类型:

  • Object 对象
  • array 数组
  • function 函数
  • RegExp 正则
  • Date 日期

判断数据类型的关键字

  • typeof 操作符
  • toString

以上几种方法都可以用来判断数据类型。他们各有各的用途。

typeof

适合判断number、string、boolean、undefined。判断其他类型不准确。比如:typeof [] == Object

typeof 1
typeof '1'
typeof false
typeof undefined
toString
Object.prototype.toString.call(1) 			// [object Number]
Object.prototype.toString.call('1')			// [object String]
Object.prototype.toString.call(false)		// [object Boolean]
Object.prototype.toString.call([])			// [object Array]
Object.prototype.toString.call(null) 		// [object Null]
Object.prototype.toString.call(undefined)	// [object Undefined]
Object.prototype.toString.call(Symbol())	// [object Symbol]

建议直接使用的tostring方法来判断数据类型。

函数封装

数据类型判断函数封装。

是否为数字类型
function isNumber(number){
    return Object.prototype.toString.call(number).toLowerCase() == '[object number]' ? true : false
}
是否为字符串
function isString(string){
    return Object.prototype.toString.call(string).toLowerCase() == '[object string]' ? true : false
}
是否为布尔类型
function isBool(bool){
    return Object.prototype.toString.call(bool).toLowerCase() == '[object boolean]' ? true : false
}
是否为函数
function isFunction(function){
    return Object.prototype.toString.call(function).toLowerCase() == '[object function]' ? true : false
}
是否为数组
function isArray(array){
    return Object.prototype.toString.call(array).toLowerCase() == '[object array]' ? true : false
}
是否为对象
function isObject(object){
    return Object.prototype.toString.call(object).toLowerCase() == '[object object]' ? true : false
}
是否为null
function isNull(null){
    return Object.prototype.toString.call(null).toLowerCase() == '[object null]' ? true : false
}
是否为undefined
function isUndefined(undefined){
    return Object.prototype.toString.call(undefined).toLowerCase() == '[object undefined]' ? true : false
}
是否为Symbol
function isSymbol(symbol){
    return Object.prototype.toString.call(symbol).toLowerCase() == '[object symbol]' ? true : false
}
是否为 htmldocument
function isDocument(htmldocument){
    return Object.prototype.toString.call(htmldocument).toLowerCase() == '[object htmldocument]' ? true : false
}