js中七种基本数据类型
number- 用于表示整数和浮点数,例如:
42、3.14 - 特殊值:
NaN(非数字)、Infinity(无穷大)
- 用于表示整数和浮点数,例如:
string- 表示文本数据,例如:
"hello"、'world'。 - 使用单引号、双引号或反引号(模板字符串)定义。
- 表示文本数据,例如:
boolean- 逻辑值,只有
true或false
- 逻辑值,只有
undefined- 表示变量未定义或未赋值,默认值为
undefined
- 表示变量未定义或未赋值,默认值为
null- 表示空值(注意:
typeof null返回"object",这是历史遗留问题)
- 表示空值(注意:
symbol(ES6 新增)- 表示唯一的、不可变的值,用于对象属性的键,例如:
Symbol('id')
- 表示唯一的、不可变的值,用于对象属性的键,例如:
bigint(ES2020 新增)- 表示任意精度的整数,例如:
123n
- 表示任意精度的整数,例如:
1、typeof
- typeof可以判断除null以外的基本数据类型。
- typek判断引用类型,除了function以外,其他的都返回object。
typeof 42; // "number"
typeof "hello"; // "string"
typeof true; // "boolean"
typeof undefined; // "undefined"
typeof null; // "object" (历史遗留 bug)
typeof Symbol(); // "symbol"
typeof 100n; // "bigint"
typeof判断原理
typeof是通过将值转换成二进制来判断类型的,对于二进制前三位是0的统一识别为对象,而所有引用类型转换成二进制前三位都是0,null的二进制全是0。
2、instanceof
instanceof是js中的一个运算符,用于检测一个对象是否是某个构造函数的实例,能准确判断引用类型,判断的机制是:通过对象的隐式原型来查找是否等于右边的prototype
基本语法
object instanceof Constructor
- object:要检测的对象
- Constructore:某个构造函(或类)
返回值
true:如果object是Constructor的实例(或其原型链上有Constructore.prototype)
false:否则
const arr = [1, 2, 3];
console.log(arr instanceof Array); // true
console.log(arr instanceof Object); // true(因为 Array 继承自 Object)
3、Object.prototype.toString.call()
Object.prototype.toString.call()是js中一种常用的类型检测方法,它能够准确判断任意值的类型。
基本原理
-
Object.prototype.toString.call()是所有对象继承的方法,返回一个表示对象的字符串。
-
.call()方法运行我们指定
this的上下文,从而可以对任何值调用此的方法
使用方式
Object.prototype.toString.call(value)
返回值
该方法返回格式为[object Type]的字符串,其中Type是对象的类型:
Object.prototype.toString.call([]) // "[object Array]"
Object.prototype.toString.call({}) // "[object Object]"
Object.prototype.toString.call('') // "[object String]"
Object.prototype.toString.call(123) // "[object Number]"
Object.prototype.toString.call(true) // "[object Boolean]"
Object.prototype.toString.call(null) // "[object Null]"
Object.prototype.toString.call(undefined) // "[object Undefined]"
Object.prototype.toString.call(new Date()) // "[object Date]"
Object.prototype.toString.call(/regex/) // "[object RegExp]"
Object.prototype.toString.call(function(){}) // "[object Function]"
优势
- 准确性强:比typeof和instanceof更可靠
- 适用范围广:可以检测所有js内置类型
- 一致性:对所有类型返回统一格式的字符串
4、Array.isArray()
Array.isArray() 是 JavaScript 中用于检测一个值是否为数组的内置方法
- 用于确定传递的值是否是一个数组
- 返回true或false
总结
在 JS 开发中,准确判断变量类型是常见的需求。本文全面对比了四种主要的类型检测方法:typeof、instanceof、Array.isArray() 和 Object.prototype.toString.call()。以下是关键总结:
| 场景 | 推荐方法 |
|---|---|
| 检测基本类型 | typeof |
| 检测数组 | Array.isArray() |
| 检测自定义类实例 | instanceof |
| 需要最精确的类型判断 | Object.prototype.toString.call() |
| 跨窗口/iframe 环境 | Array.isArray() 或 Object.prototype.toString.call() |
终极建议
- 简单场景用简单方法:优先使用专门的检测方法(如
Array.isArray()) - 复杂场景用全能方法:当需要处理未知类型时,
Object.prototype.toString.call()最可靠 - 注意性能:在性能关键代码中,
typeof通常最快 - 一致性优先:项目中应统一类型检测方式,避免混用造成混淆