前端思考日记(2021/1/24)
写下自己的思考是个好习惯,可以总结自己的学习和智慧,巩固知识,也可以让自己不犯同样错误。希望自己可以坚持下来。
js 数据类型
基本数据类型: Number、String、Boolean、Null、undefined、symbol
复杂数据类型: Object 和里面包含的 Function、Array、RegExp、Data
数据类型判断
数据类型判断的方法有很多种,如: typeof
、instanceof
、Obejct.prototype.toString.call()
、constructor
typeof
typeof
可以直接返回数据的类型,但是有一些类型是判断不出来的。
基本类型中,**null ** 类型会判断成 object
复杂类型中,除了 function 类型,其他一律判断成 object
const allType = {
string: "1",
number: 1,
bool: true,
symbol: Symbol('symbol'),
null_: null,
undefined_: undefined,
obj: {},
arr: [],
func: () => { },
date: new Date,
reg: /RegExp/
}
Object.keys(allType).forEach(key => {
console.log(key, typeof allType[key])
})
/*
string string
number number
bool boolean
symbol symbol
null_ object
undefined_ undefined
obj object
arr object
func function
date object
reg object
*/
instanceof
instanceof
可以判断所有的对象类型
但是判断不了基本数据类型
a instanceof A
的判断依据是:a 的原型链上面有没有 A.prototype
const string = "1"
const number = 1
const bool = true
const symbol = Symbol('symbol')
const null_ = null
const undefined_ = undefined
const obj = {}
const arr = []
const func = ()=>{}
const date = new Date
const reg = /RegExp/
console.log(obj instanceof Object); // true
console.log(arr instanceof Array); // true
console.log(func instanceof Function); // true
console.log(date instanceof Date); // true
console.log(reg instanceof RegExp); // true
Object.prototype.toString.call
这种方法可以判断所有数据类型
返回形式是:[object 类型名]
const allType = {
string: "1",
number: 1,
bool: true,
symbol: Symbol('symbol'),
null_: null,
undefined_: undefined,
obj: {},
arr: [],
func: () => { },
date: new Date,
reg: /RegExp/
}
Object.keys(allType).forEach(key => {
console.log(key, Object.prototype.toString.call(allType[key]))
})
/*
string [object String]
number [object Number]
bool [object Boolean]
symbol [object Symbol]
null_ [object Null]
undefined_ [object Undefined]
obj [object Object]
arr [object Array]
func [object Function]
date [object Date]
reg [object RegExp]
*/
变量.proto.constructor
直接找变量的原型是哪里来的,就可以知道这是什么类型的
返回形式是:[Function: 类型]
但是 null 和 undefined 不能通过这种方式判断
const allType = {
string: "1",
number: 1,
bool: true,
symbol: Symbol('symbol'),
// null_: null,
// undefined_: undefined,
obj: {},
arr: [],
func: () => { },
date: new Date,
reg: /RegExp/
}
Object.keys(allType).forEach(key => {
console.log(key, allType[key].__proto__.constructor)
})
/*
string [Function: String]
number [Function: Number]
bool [Function: Boolean]
symbol [Function: Symbol]
obj [Function: Object]
arr [Function: Array]
func [Function: Function]
date [Function: Date]
reg [Function: RegExp]
*/
总结
四种方法中,Object.prototype.toString.call
这个方法个人感觉最好,可以直接判断所有类型
唯一的缺点是 IE 早期版本用这个方法无法判断 null 类型
typeof
+ instanceof
+ ===null
也可以判断所有类型,且网上大多是用这种方法