数据类型 & typeof
数据类型
- 原始类型
- 对象类型
typeof
1. 使用
// 对象
typeof {a:1}; // "object"
// 数组
typeof [1,2,3]; // "object"
// 类创建的对象
typeof new Date();// "object"
// 函数
typeof function(){}; // "function" 特殊⭐️
// null
typeof null;// "object" 历史遗留:因为null在以前表示NULL指针(0x00)typeof无法分别Array和Object
2. 解决方案与实践
- 直接使用
===来规避使用typeof
if(testObject === null){
return true;
}- 判断是否为数组
if(Array.isArray(testArr)){
return true;
}- 通杀判断 Object.prototype.toString.call()
Object.prototype.toString.call(null);// "[object Null]"
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]"