javascript 检测数据类型的方法

js检测数据类型的方法

1、typeof 方法

  • 在计算机底层基于数据类型的值(二进制)进行检测
  • typeof null 检测出是object,由于对象存储在计算机中是以000开始的二进制进行存储,null也是,所以检测出来的结果是对象。
  • typeof 检测普通对象、数组对象、正则对象、日期对象都是object

2、instanceof 方法

  • 底层机制:只要当前类出现在实例的原型链上,结果都是true
let arr = [];
arr instanceof Array; // true
arr instanceof RegExp; // false 
arr instanceof Object; // true
  • 由于可以随意修改原型的指向,所以检测出来的结果不准
function Fn(){
	this.x = 100;
}
Fn.prototype = Object.create(Array.prototype);
let f = new Fn;
console.log(f instanceof Array); // true
  • 不能检测基本数据类型
1 instanceof Number; // false

3、constructor 方法

  • 可以检测基本数据类型和对象
let arr = [];
arr.constructor === Array; // true
arr.constructor === RegExp; // false
arr.constructor === Object; // false

let n = 1;
n.constructor === Number; // true
  • constructor 可以随意修改,所以也不准确
Number.prototype.constructor = 'AA';
let n = 1;
n.constructor === Number; // false

4、Object.prototype.toString.call([value])方法

  • 标准检测数据类型的方法:Object.prototype.toString 不是转换为字符串,是返回当前实例所属类的信息
let obj = { name: '张三'};
obj.toString(); // "[object Object]"
  • 标准检测的方法
Object.prototype.toString.call(1); // "[object Number]"
Object.prototype.toString.call(NaN); // "[object Number]"
Object.prototype.toString.call(""); // "[object String]"
Object.prototype.toString.call(true); // "[object Boolean]"
Object.prototype.toString.call(Symbol('xx')); // "[object Symbol]"
Object.prototype.toString.call({}); // "[object Object]"
Object.prototype.toString.call([]); // "[object Array]"
Object.prototype.toString.call(/^$/); // "[object RegExp]"
Object.prototype.toString.call(new Date()); // "[object Date]"
Object.prototype.toString.call(function(){}); // "[object Function]"
Object.prototype.toString.call(null); // "[object Null]"
Object.prototype.toString.call(undefined); // "[object Undefined]"
  • 10
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值