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
undefinedundefined
nullobject
Symbol 数据symbol
NaNnumber
Infinitynumber
函数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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

朝阳39

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值