在JavaScript中,你可以使用多种方法来判断变量的数据类型。以下是一些常用的方法:
1. typeof
操作符
typeof
是最常用的方法之一,它可以返回一个字符串,表示未经计算的操作数的类型。
typeof undefined; // "undefined"
typeof true; // "boolean"
typeof "abc"; // "string"
typeof 123; // "number"
typeof {}; // "object"
typeof []; // "object",注意:数组也是对象
typeof null; // "object",这是一个历史遗留问题
typeof function(){}; // "function"
typeof Symbol(); // "symbol"
2.instanceof
操作符
instanceof
运算符用于检测构造函数的 prototype
属性是否出现在某个实例对象的原型链上。
var arr = [];
arr instanceof Array; // true
arr instanceof Object; // true,因为数组也是对象
3. Object.prototype.toString.call()
方法
Object.prototype.toString
方法可以准确判断一个值的类型,它返回一个表示该对象的字符串。
Object.prototype.toString.call(undefined); // "[object Undefined]"
Object.prototype.toString.call(null); // "[object Null]"
Object.prototype.toString.call(true); // "[object Boolean]"
Object.prototype.toString.call(123); // "[object Number]"
Object.prototype.toString.call("abc"); // "[object String]"
Object.prototype.toString.call({}); // "[object Object]"
Object.prototype.toString.call([]); // "[object Array]"
Object.prototype.toString.call(function(){}); // "[object Function]"
Object.prototype.toString.call(/regex/); // "[object RegExp]"
4. Array.isArray()
方法
为了弥补 typeof
在判断数组时的不足,ECMAScript 5 引入了 Array.isArray()
方法
Array.isArray([]); // true
Array.isArray({}); // false
注意事项
typeof
对于基本数据类型(Undefined
,Null
,Boolean
,Number
,String
,Symbol
)是非常有用的,但对于引用类型(如Array
,Function
,Object
)则不那么精确,因为它们都会返回"object"
。instanceof
在判断对象的具体类型时很有用,但它不能正确判断原始类型。Object.prototype.toString.call()
是判断数据类型最准确的方法,因为它可以区分所有内置类型。- 对于数组类型,推荐使用
Array.isArray()
方法。