JavaScript typeof 用法:判断类型与常见例外
typeof 用 "number"、"string" 等字符串报告值的类型。null 和数组都返回 "object",NaN 返回 "number"。区分这些情况时还要做额外检查。
语法与可能返回的字符串
typeof 42; // "number"
typeof "42"; // "string"
typeof (1 + "2"); // "string"
typeof 是运算符。括号可用于组合表达式。通过 typeof value === "number" 等方式比较结果字符串。类型取决于变量当前持有的值,BigInt 是用于整数的独立原始类型。
在完整示例中比较多个值
将代码以 UTF-8 保存为 typeof-demo.html 后打开。脚本对每个值执行同样的检查并生成结果表。短箭头函数用来演示函数值。
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Compare typeof results</title>
</head>
<body>
<h1>Compare typeof results</h1>
<table>
<thead><tr><th>Value</th><th>typeof result</th></tr></thead>
<tbody id="types"></tbody>
</table>
<button id="tdz" type="button">Test let before initialization</button>
<pre id="output"></pre>
<script>
const samples = [
["String", "hello"], ["Number", 42], ["NaN", NaN],
["Infinity", Infinity], ["BigInt", 42n], ["Boolean", true],
["Symbol", Symbol("id")], ["Function", () => {}],
["Array", []], ["null", null], ["Plain object", {}],
["undefined", undefined]
];
const tbody = document.getElementById("types");
for (const [label, value] of samples) {
const row = document.createElement("tr");
for (const text of [label, typeof value]) {
const cell = document.createElement("td");
cell.textContent = text;
row.appendChild(cell);
}
tbody.appendChild(row);
}
const output = document.getElementById("output");
document.getElementById("tdz").addEventListener("click", () => {
try {
const result = typeof later;
let later = 1;
output.textContent = result;
} catch (error) {
output.textContent = error.name;
}
});
</script>
</body>
</html>
数字、NaN 和 Infinity 返回 number。数组、null 和普通对象返回 object,函数返回 function。BigInt 和 Symbol 各有自己的结果。可以修改一个样本后重新加载。Test let before initialization 按钮捕获并显示预期的 ReferenceError。
分别检查数组、null 和有限数字
const value = [];
Array.isArray(value); // true
value === null; // false
Number.isNaN(NaN); // true
Number.isFinite(12); // true
Number.isFinite("12"); // false
Number.isFinite(Infinity); // false
用 Array.isArray() 检查数组,用 value === null 检查 null。Number.isFinite() 会排除 NaN 和无穷大,不会自动转换数字字符串。若要接收文本数字,可先检查格式,再验证转换结果。
未声明名称与暂时性死区
typeof neverDeclaredName; // usually "undefined"
{
// typeof waiting; // would throw ReferenceError
let waiting = 1;
console.log(typeof waiting); // "number"
}
未声明的名称通常返回 "undefined"。同一作用域内的 let、const、class 在初始化前处于暂时性死区(TDZ),无法访问。示例把会报错的行注释掉了。typeof 1 + "x" 得到 "numberx",而 typeof (1 + "x") 得到 "string"。document.all 有兼容性特例。
验证对象中需要的字段
在开发者工具 Console 中执行代码。检查商品数据时先排除 null 和数组,再判断名称是否为字符串,价格是否通过 Number.isFinite() 且不小于 0。
{
function isProduct(value) {
return value !== null
&& typeof value === "object"
&& !Array.isArray(value)
&& typeof value.name === "string"
&& Number.isFinite(value.price)
&& value.price >= 0;
}
console.log(isProduct({ name: "Notebook", price: 0 })); // true
console.log(isProduct({ name: "Notebook", price: "12" })); // false
console.log(isProduct({ name: "Notebook", price: NaN })); // false
console.log(isProduct(null)); // false
}
依次输出 true、false、false、false。0 是有效价格,字符串 "12" 和 NaN 会被拒绝。示例只检查这些字段。如果名称不能为空,可先去掉首尾空白再判断长度。




