js检查数据类型的方法

1.通过 instanceof 判断返回一个布尔值

用于检验构造函数的prototype属性是否出现在对象的原型链中的任何位置

let a = [];
a instanceof Array; //true
let b = {};
b instanceof Array; //false

在上方代码中,instanceof运算符检测Array.prototype属性是否存在于变量a的原型链上,显然a是一个数组,拥有Array.prototype属性,所以为true。

2.通过constructor判断

实例的构造函数属性constructor指向构造函数,那么通过constructor属性也可以判断是否为一个数组。

let a = [1,3,4];
a.constructor === Array;//true
3.typeof 检查出来的null {} [] 都是一个对象
4.Object.prototype.toString.call() 所有的类型都可以被检测出来 就算是更改原型一样可以输出 原来的数据类型
console.log(Object.prototype.toString.call([]));//{object Array}
5.$.type() 需要引入jQuery
$.type(null)     //  {object    Null}
$.type([])    //  {object    Array}
3.Array.isArray() 用于确定传递的值是否是一个数组,返回一个布尔值 --es5(常用)
let a = [1,2,3]
Array.isArray(a);//true

posted @ 2021-01-11 21:29  歇歇吧  阅读(42)  评论(0编辑  收藏  举报