JavaScript的变量没有类型,可以任意赋值,但是变量的值有类型
基础数据类型
- string
- boolean
- number
- null
- undefined
- symbol
- bigint
引用数据类型
- object
在object类型基础上派生出的引用类型
- Function
- Array
- Date
- 其他
数据类型检测
typeof 检测
typeof "" // string
typeof 1 // number
typeof false // false
typeof Symbol(1) // symbol
typeof BigInt(1) // bigint
var a
typeof a // undefined
typeof null // object, javascript的一个bug
typeof alert // function
typeof 检测其他对象的时候都返回object, 但不是所有typeof 的值为 object的都是对象, null是个很特殊的情况
null和对象的检测
如上所说使用typeof不能准确检测null和object
可以直接检测null
var foo = null;
foo === null
检测对象的话可以
const foo = {};
typeof foo === "object" && foo !== null
引用类型检测(instanceof)
基础语法
object instanceof constructor
object 需要是一个对象
constructor 是一个构造函数
如果object 是constructor 或 原型链上的构造函数的实例。则为true;其他情况均返回false
所以 ,数字是一个坑,string同理
0 instanceof Number // false
1 instanceof Number // false
new Number(0) instanceof Number // true
new Number(1) instanceof Number // true
Number(1) instanceof Number // false
超级检测法
本质: JavaScript万物皆对象,对象的原型上有toString方法;原始的(原型链)对象的toString方法会返回数据类型信息
例如
Object.prototype.toString.call() // [object Undefined]
Object.prototype.toString.call(null) // [object Null]
Object.prototype.toString.call(1) // [object Number]
Object.prototype.toString.call(false) // "[object Boolean]"
Object.prototype.toString.call([]) // "[object Array]"
Object.prototype.toString.call({}) // "[object Object]"
Object.prototype.toString.call(() => {}) // "[object Function]"
所以可以适当封装
function isType(value, type) {
return Object.prototype.toString.call(value) === `[object ${type}]`
}
// 进一步封装
function isArray(value) {
return isType(value, "Array")
}
// 其他类型暂不赘述...
Object.prototype.toString 语言标准
华丽的分割线
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。