[js] “===“ 及 typeof

"=== "是 JavaScript 的严格相等运算符,和 ==(宽松相等)有本质区别:

运算符行为
==会尝试类型转换后再比较
===值和类型都相等才为 true,不做类型转换

在本例中:
typeof window.drawPolyline === 'function'
typeof 的返回值永远是字符串(‘function’、‘undefined’、‘object’ 等)
和字符串 ‘function’ 比较,=== 直接比对,类型一致、值一致
如果写成 == 效果相同,因为两边都是 string 类型。但 === 是 JS 社区推荐做法——显式声明"我不需要类型转换",避免埋坑。

举个典型的坑:

0=='0'// true ← 字符串 '0' 被转成数字 00==='0'// false ← 类型不同,直接 false

所以在生产代码中统一用 === 是好习惯——明确、可预测
typeof 返回值表(共 8 种):

返回值触发条件示例
“undefined”未声明 / 已声明未赋值 / 显式赋 undefinedtypeof x、typeof undefined
“boolean”布尔值typeof true、typeof false
“number”数字(含 NaN、Infinity)typeof 42、typeof NaN、typeof Infinity
“bigint”BigInt 大整数typeof 1n、typeof BigInt(42)
“string”字符串typeof “hello”、typeof ‘’
“symbol”Symbol 唯一值typeof Symbol()、typeof Symbol.iterator
“function”函数(含 class)typeof function(){}、typeof class {}、typeof Math.max
“object”对象、数组、null、正则……typeof {}、typeof []、typeof null、typeof /a/

关键判断逻辑
typeof 本质上取的是 JS 引擎内部的 [[Type]] 标签,不是原型链推断:

值.内部类型标签 ──→ typeof 返回值
三个著名陷阱
① null 返回 “object”

typeofnull==="object"// true ← JS 历史 bug,永远如此

检查 null 必须用:

x===null

② 数组返回 “object”

typeof[1,2,3]==="object"// true

检查数组用:

Array.isArray([1,2,3])// true

③ NaN 返回 “number”

typeofNaN==="number"// true ← NaN 的类型是数字

typeof NaN === “number” // true ← NaN 的类型是数字

Number.isNaN(x)

undefined → “undefined”
null → “object” ← 陷阱
true/false → “boolean”
数字/NaN → “number”
1n → “bigint”
“str” → “string”
Symbol() → “symbol”
function → “function” ← 唯一的非 “object” 引用类型
其它全 → “object” ← 对象、数组、正则、null 都落这里