1.Object.prototype.toString()
使用typeof bar === "object"检测”bar”是否为对象有什么缺点?如何避免?
用 typeof 是否能准确判断一个对象变量,答案是否定的,null 的结果也是 object,数组的结果也是 object,有时候我们需要的是 "纯粹" 的 object 对象。如何避免呢?比较好的方式是:
console.log(Object.prototype.toString.call(obj) === "[object Object]");
判断类型函数代码实现如下:
const getType = (obj) => Object.prototype.toString.call(obj).slice(8, -1);
export function isArray(obj: any): obj is any[] {
return getType(obj) === 'Array';
}
export function isObject(obj: any): obj is { [key: string]: any } {
return getType(obj) === 'Object';
}
export function isString(obj: any): obj is string {
return getType(obj) === 'String';
}
export function isNumber(obj: any): obj is number {
return getType(obj) === 'Number' && obj === obj;
}
export function isRegExp(obj: any) {
return getType(obj) === 'RegExp';
}
export function isFile(obj: any): obj is File {
return getType(obj) === 'File';
}
export function isBlob(obj: any): obj is Blob {
return getType(obj) === 'Blob';
}
export function isUndefined(obj: any): obj is undefined {
return obj === undefined;
}
export function isFunction(obj: any): obj is (...args: any[]) => any {
return typeof obj === 'function';
}
export function isEmptyObject(obj: any): boolean {
return isObject(obj) && Object.keys(obj).length === 0;
}