0
点赞
收藏
分享

微信扫一扫

JS【详解】数据类型检测(含获取任意数据的数据类型的函数封装、typeof、检测是否为 null、检测是否为数组、检测是否为非数组/函数的对象)


【函数封装】获取任意数据的数据类型

/**
 * 获取任意数据的数据类型
 *
 * @param x 变量
 * @returns 返回变量的类型名称(小写字母)
 */
function getType(x) {
  // 获取目标数据的私有属性 [[Class]] 的值
  const originType = Object.prototype.toString.call(x); // 以字符串为例:'[object String]'
  // 获取类型属性值中' '的下标
  const spaceIndex = originType.indexOf(" ");
  // 截取类型属性值中' '到末尾']'之间的字符串
  const type = originType.slice(spaceIndex + 1, -1); // 以字符串为例:'String'
  // 将字符串转换为小写
  return type.toLowerCase(); //以字符串为例:'string'
}

typeof 运算符

适用于检测值类型( null 除外 )、函数和类的数据类型,对引用类型的数据只能得到 object

参数

返回值

数值

number

字符串

string

布尔型

boolean

undefined

undefined

null

object

Symbol 数据

symbol

NaN

number

Infinity

number

函数

function

class类

function

数组等对象

object

检测是否为 null

if (x === null) {
  console.log("x 的数据类型为 null");
}

检测是否为数组

Array.isArray(val)

val instanceof Array

Object.prototype.toString.call(val) === '[object Array]'

val?.constructor === Array

Object.getPrototypeOf(val) === Array.prototype

// isPrototypeOf() 方法用于测试一个对象是否存在于另一个对象的原型链上。
Array.prototype.isPrototypeOf(val)

检测是否为非数组/函数的对象

Object.prototype.toString.call(val) === '[object Object]'

val?.constructor === Object

Object.getPrototypeOf(val) === Object.prototype


举报

相关推荐

0 条评论