首页 > Web开发 > 详细

js检查数据类型的方法

时间:2021-01-11 23:01:15      阅读:32      评论:0      收藏:0      [点我收藏+]
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

js检查数据类型的方法

原文:https://www.cnblogs.com/33shan/p/14264476.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!