数据类型和typeof的陷阱

📅 2026/7/9 8:35:38
数据类型和typeof的陷阱
目标typeof null 为什么返回object如何准确判断一个值为数组一、JavaScript数据类型1、原始类型string、number、boolean、null、undefined、symbol、bigint2、对象类型object包含ArrayFunction等二、typeof是什么一元操作符返回操作数类型的字符串表示typeof的两大核心陷阱typeof meng; //string typeof 123; //number typeof true; //boolean typeof Symbol(id); //symbol typeof 123n; //bigint typeof undefind; //undefind typeof {a:1}; //object typeof [1,2,3]; //object 注意typeof不能分辨数组 typeof new Date(); //object typeof function(){}; //function 特殊1、typeof null为什么是object这是js早期版本的历史遗留bug在js早期实现中null的底层表示是NULL指针0x00对象的类型标签恰好也是0typeof错误的将其识别为对象bug保留原因涉及范围太广改动可能影响到网站解决方案使用严格相等运算符 const myVar null; if(myVar null){ console.log(null) }2、无法区分具体对象类型typeof无法区分Array和object解决方案 Array.isArray( arr )const arr [ ]; console.log(Array.isArray(arr)); //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]