js如何判断变量的类型

js如何判断变量的类型
最新回答
挂科比挂科难

2020-12-04 05:24:29

在 JavaScript 中,判断变量类型主要依赖 typeof 运算符,其返回一个字符串描述变量的类型。以下是具体方法及注意事项:

1. 使用 typeof 运算符

语法

typeof variable;

返回值类型

  • "undefined":变量未声明或未赋值。
  • "null":变量值为 null(但 typeof null 返回 "object",需注意)。
  • "boolean":布尔值(true 或 false)。
  • "number":数字(包括整数、浮点数、NaN、Infinity)。
  • "string":字符串。
  • "bigint":大整数(以 n 结尾,如 10n)。
  • "symbol":Symbol 值(ES6 新增)。
  • "object":对象(包括普通对象、数组、函数、正则表达式、Date 等),或 null(历史遗留问题)。

示例

console.log(typeof 10); // "number"console.log(typeof "Hello"); // "string"console.log(typeof true); // "boolean"console.log(typeof undefined); // "undefined"console.log(typeof null); // "object"(特殊情况)console.log(typeof {}); // "object"console.log(typeof []); // "object"(数组)console.log(typeof function() {}); // "function"2. 特殊情况处理
  • null 的类型:typeof null 返回 "object",这是 JavaScript 的历史遗留问题。若需严格判断 null,需直接比较:

    const value = null;console.log(value === null); // true
  • 数组的类型:typeof [] 返回 "object",需用 Array.isArray() 判断:

    console.log(Array.isArray([])); // true
  • 函数的类型:typeof function() {} 返回 "function",但函数本质是对象,此行为是语言特例。

3. 更严格的类型检查方法
  • instanceof 运算符:检查对象是否为特定类的实例,适用于自定义对象或内置对象(如 Array、Date):

    const arr = [1, 2, 3];console.log(arr instanceof Array); // true
  • Object.prototype.toString.call():返回对象的内部 [[Class]] 属性,可精确区分所有类型(包括内置对象):

    console.log(Object.prototype.toString.call([])); // "[object Array]"console.log(Object.prototype.toString.call(null)); // "[object Null]"console.log(Object.prototype.toString.call(10)); // "[object Number]"
  • ES6 的 Array.isArray()、Symbol.for() 等:针对特定类型的辅助方法,如判断数组、Symbol 等。

4. 最佳实践建议
  • 基础类型判断:优先使用 typeof(简单场景)。
  • 严格对象类型判断

    数组:Array.isArray()

    null:直接比较 === null

    其他对象:instanceof 或 Object.prototype.toString.call()

  • 避免依赖 typeof 判断复杂对象:因其对数组、函数等返回 "object",易引发歧义。
总结
  • typeof:快速判断基础类型,但需注意 null 和对象类型的局限性。
  • 严格方法:结合 ===、instanceof、Array.isArray() 等处理特殊情况。
  • 精确判断:使用 Object.prototype.toString.call() 覆盖所有场景。

通过合理选择方法,可准确判断 JavaScript 变量的类型,避免潜在问题。