内置类型
JavaScript 有八种内置类型
null、undefined、boolean、number、string、symbol、bigint、object
我们可以用 typeof 运算符来查看值的类型(注:变量没有类型 但它们持有的值有类型),它返回的是类型的字符串。
typeof undefined === 'undefined'; // true
typeof true === 'boolean'; // true
typeof 123 === 'number'; // true
typeof "str" === 'string'; // true
typeof {} === 'object' // true
typeof Symbol() === 'symbol' // true
typeof 999n === 'bigint' // true
有没有注意到 null 类型不在上述列表中。它比较特殊,typeof 对它的处理存在 bug。
typeof null === 'object'; // true
// 此 bug 由来已久,也许永远不会修复了。。。
null 是 “假值” (falsy 或 false-like)也是唯一一个用 typeof 检测会返回 “object” 的基本类型。那么我们怎么来检测 null 值呢?
// 需要使用复合条件
if(!n && typeof n === "object") {
console.log(n) // null
}
typeof 的其他特殊情况:
typeof function fn() {/* ... */} === 'function'; // true
typeof [] === "object"; //true
// 注 JavaScript 的内置类型没有 function,我们可以把 function 和 数组称为 object 的子类型
undefined 和 undeclared
已经在作用域中声明但还没有赋值的变量,是 undefined(未定义) 的。还没有在作用域中声明过的变量,是 undeclared(未声明) 的。
例如:
let a;
console.log(a); // undefined
console.log(b); // ReferenceError: b is not defined
我们访问 undeclared 的变量浏览器会报错,但是奇怪的是 typeof 处理 undeclared 的方式却和浏览器不同。typeof 有一个特殊的安全防范机制。
例如:
let a;
typeof a; // undefined
typeof b; // undefined
typeof 的这种安全防范机制对我们还是很有用的。可以通过 typeof 来阻止报错来检查 undeclared 变量。
例如当我们的代码依赖某个变量,但不确定上下文中是否存在时可以这样写,例如:
if(typeof a !== "undefined"){
/* ... */
}