判断变量类型的方法有以下几种:
-
typeof 操作符
typeof 操作符是 JavaScript 中最常用的判断变量类型的方法之一,可以用于判断 undefined、boolean、number、string、function 和 object 类型的变量。
优点:该方法简单、快速,适用于大多数情况下。
缺点:其中数组、对象、null 都会被判断为 object,无法判断复杂的数据类型如数组和正则表达式,其他判断都正确。typeof 'hello'; // 返回 "string" typeof 123; // 返回 "number" typeof true; // 返回 "boolean" typeof undefined; // 返回 "undefined" typeof function(){}; // 返回 "function" typeof null; // 返回 "object"
-
instanceof
instanceof 操作符可以用于判断对象是否为某个构造函数的实例。console.log(2 intanceof Number) // false console.log( [] intanceof Array ) // true 优点:可以区分复杂的数据类型如数组和正则表达式。 缺点:无法判断基本数据类型,无法判断 null 和 undefined 类型。
-
Object.prototype.toString.call()
使用 Object 对象的原型方法toString 来判断数据类型:var a = Object.prototype.toString; console.log(a.call(2)) 优点:可以判断复杂的数据类型,包括数组、正则表达式等。 缺点:需要调用 Object.prototype.toString.call() 方法,语法较复杂
-
Array.isArray()
Array.isArray() 方法可以用于判断变量是否为数组类型。优点:语法简单,只需调用 Array.isArray() 方法即可判断。 缺点:只能判断数组类型,无法判断其他数据类型。
-
constructor 属性
constructor 有两个作用,一是判断数据的类型,二是对象实例通过
constrcutor 对象访问它的构造函数。需要注意,如果创建一个对象
来改变它的原型,constructor 就不能用来判断数据类型了:function Fn(){} Fn.prototype = new Array(); var f = new Fn() console.log( f.constructor === Fn ) // false console.log( f.constructor === Array ) //true 优点:语法简单,只需访问变量的 constructor 属性即可判断。 缺点:当变量被重新赋值时,可能会出现问题,无法判断 null 和 undefined 类型。
总的来说,每种判断变量类型的方法都有其优缺点,根据实际情况选择最适合的方法。在实际使用中,可以根据需要灵活选择不同的方法来判断变量的类型。