js数据类型判断方法

javascript中常用数据类型判断方法有:typeof、instanceof、constructor、Object.prototype.toString.call()

typeof- - -可以检测出基本数据类型(除了null)

检测方法: typeof xx

优点:使用简单
缺点:复杂类型检测出来都是 object,null 也是 object

typeof操作符可以返回一个值的数据类型,例如:

typeof 123; // "number"
typeof "hello"; // "string"
typeof true; // "boolean"
typeof undefined; // "undefined"
typeof null; // "object" 注意这个结果是历史遗留问题
typeof {}; // "object"
typeof []; // "object"
typeof function(){}; // "function"

需要注意的是,typeof操作符对于null值的判断会返回"object",这是历史遗留问题,因此需要特别注意。

instanceof 原型链检测

检测方法:xx instanceof yy - - -检测 xx 的原型链上是否 存在 yy

优点:能检测出引用类型
缺点:instanceof 不能检测出基本类型,且不能跨 iframe

String 和 Date 对象属于 Object 对象

instanceof运算符可以用来判断一个对象是否是某个构造函数的实例。例如:

const a = new Date();
a instanceof Date; // true
a instanceof Object; // true
a instanceof Array; // false

需要注意的是,instanceof运算符只能用来判断对象的类型,不能用来判断基本数据类型的类型。

constructor 构造函数检测

检测方法:xx.constructor- - -返回 xx 的 构造函数

优点:基本能检测所有的类型(除了 null 和 undefined )
缺点:constructor 容易被修改,也不能跨iframe

Object.prototype.toString.call()

检测方法:Object.prototype.toString.call(xx)

优点:可检测所有的类型
缺点:IE6下,undefined 和 null 均为 Object

注意以下特殊情况:

Object.prototype.toString方法可以返回一个对象的数据类型,例如:

Object.prototype.toString.call(123); // "[object Number]"
Object.prototype.toString.call("hello"); // "[object String]"
Object.prototype.toString.call(true); // "[object Boolean]"
Object.prototype.toString.call(undefined); // "[object Undefined]"
Object.prototype.toString.call(null); // "[object Null]"
Object.prototype.toString.call({}); // "[object Object]"
Object.prototype.toString.call([]); // "[object Array]"
Object.prototype.toString.call(function(){}); // "[object Function]"

需要注意的是,Object.prototype.toString方法返回的是一个字符串,需要使用call方法来改变this指向。

Array.isArray方法

Array.isArray方法可以用来判断一个值是否是数组类型,例如:

Array.isArray([]); // true
Array.isArray({}); // false
Array.isArray("hello"); // false
Array.isArray(123); // false

需要注意的是,Array.isArray方法只能用来判断数组类型,不能用来判断其他数据类型的类型。

总之,JavaScript中有多种方法可以用来判断数据类型,每种方法都有其特点和适用范围,需要根据不同的场景进行选择。

展开阅读全文

页面更新:2024-03-13

标签:数据类型   方法   数组   原型   函数   缺点   优点   对象   类型   操作

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2008-2024 All Rights Reserved. Powered By bs178.com 闽ICP备11008920号-3
闽公网安备35020302034844号

Top