typeof常见易错点

📅 发布时间:2026/7/11 3:19:32 👁️ 浏览次数:
typeof常见易错点
基本用法// 数值 typeof 37 number; typeof 3.14 number; typeof 42 number; typeof Math.LN2 number; typeof Infinity number; typeof NaN number; // 尽管它是 Not-A-Number (非数值) 的缩写 typeof Number(1) number; // Number 会尝试把参数解析成数值 typeof Number(shoe) number; // 包括不能将类型强制转换为数字的值 typeof 42n bigint; // 字符串 typeof string; typeof bla string; typeof template literal string; typeof 1 string; // 注意内容为数字的字符串仍是字符串 typeof typeof 1 string; // typeof 总是返回一个字符串 typeof String(1) string; // String 将任意值转换为字符串比 toString 更安全 // 布尔值 typeof true boolean; typeof false boolean; typeof Boolean(1) boolean; // Boolean() 会基于参数是真值还是虚值进行转换 typeof !!1 boolean; // 两次调用 !逻辑非运算符相当于 Boolean() // Symbols typeof Symbol() symbol; typeof Symbol(foo) symbol; typeof Symbol.iterator symbol; // Undefined typeof undefined undefined; typeof declaredButUndefinedVariable undefined; typeof undeclaredVariable undefined; // 对象 typeof { a: 1 } object; // 使用 Array.isArray 或者 Object.prototype.toString.call // 区分数组和普通对象 typeof [1, 2, 4] object; typeof new Date() object; typeof /regex/ object; // 下面的例子令人迷惑非常危险没有用处。避免使用它们。 typeof new Boolean(true) object; typeof new Number(1) object; typeof new String(abc) object; // 函数 typeof function () {} function; typeof class C {} function; typeof Math.sin function;易错点一在 JavaScript 最初的实现中JavaScript 中的值是由一个表示类型的标签和实际数据值表示的。对象的类型标签是 0。由于null代表的是空指针大多数平台下值为 0x00因此null 的类型标签是 0typeof null也因此返回object。// JavaScript 诞生以来便如此 typeof null object;易错点二所有使用 new 调用的构造函数都将返回非基本类型object或function。大多数返回对象但值得注意的例外是 Function它返回一个函数。const str new String(String); const num new Number(100); typeof str; // object typeof num; // object const func new Function(); typeof func; // function易错点三typeof操作符的优先级高于加法等二进制操作符。因此需要用括号来计算加法结果的类型。// 括号有无将决定表达式的类型。 const someData 99; typeof someData Wisen; // number Wisen typeof (someData Wisen); // string易错点四typeof通常总是保证为它提供的任何操作数返回一个字符串。即使使用未声明的标识符typeof也会返回undefined而不是抛出错误。typeof undeclaredVariable; // undefined但在加入了块级作用域的 let 和 const 之后在其被声明之前对块中的let和const变量使用typeof会抛出一个 ReferenceError。块作用域变量在块的头部处于“暂存死区”直至其被初始化在这期间访问变量将会引发错误。typeof newLetVariable; // ReferenceError typeof newConstVariable; // ReferenceError typeof newClass; // ReferenceError let newLetVariable; const newConstVariable hello; class newClass {}