相关概念
js是一门弱语言,它在声明变量时无需确定变量的类型,js在运行时会自动判断。那么如何判断一个变量的类型呢,js提供了typeof运算符用来检测一个变量的类型。
typeof是一个运算符,有2种使用方式:typeof(表达式)和typeof 变量名,第一种是对表达式做运算,第二种是对变量做运算。
返回值
1. 'undefined' //未定义的变量或值
2. 'boolean' //布尔类型的变量或值
3. 'string' //字符串类型的变量或值
4. 'number' //数字类型的变量或值
5. 'object' //对象类型的变量或值,或者null(这个是js历史遗留问题,
//将null作为object类型处理)
6. 'function' //函数类型的变量或值
7. "symbol" //Symbol (ECMAScript 2015 新增)
8. "bigint" // 大数
// 例子
typeof 1 === 'number'; // true
typeof 'str' === 'string'; // string
.....
如何安全的准确的判断类型
Object.prototype.toString.call
function typeOf( data ){
const typeMap = {
'[object Boolean]': 'Boolean',
'[object Number]': 'Number',
'[object String]': 'String',
'[object Undefined]': 'Undefined',
'[object Null]': 'Undefined',
'[object Symbol]': 'Symbol',
'[object Object]': 'Object',
'[object Array]': 'Array',
'[object Function]': 'Function',
'[object Date]': 'Date'
};
return typeMap(Object.prototype.toString.call(data));
}