Skip to main content

JavaScript 是门热情洋溢的语言,但它的“类型系统”却让人怀疑自己是不是走错片场。

你以为的字符串,其实是个对象?你以为的 null 是空值,其实是个 object?

本节,我们就来揭开 JS 数据类型的真实面目。

🧩 JavaScript 的七大基础类型

JavaScript 有 7 个基本(原始)数据类型

类型名说明举例
string字符串"hello"
number数值(整数、小数、NaN、Infinity)42, 3.14
boolean布尔值(真或假)true, false
null空值,表示“无”null
undefined未定义undefined
symbol独一无二的值(ES6 引入)Symbol("id")
bigint超大整数(ES2020 引入)1234567890123456789n

🎭 typeof 的尴尬小毛病

typeof "JS"; // string
typeof 123; // number
typeof true; // boolean
typeof null; // ❗ object(这是个历史遗留 bug)

经典坑:

typeof null;       // object
typeof NaN; // number
typeof []; // object
typeof {}; // object
typeof (() => {}); // function

🧪 对象类型 vs 原始类型

let x = 1;
let y = x;
y++;
console.log(x); // 1

let obj1 = { name: "JS" };
let obj2 = obj1;
obj2.name = "TypeScript";
console.log(obj1.name); // TypeScript

🕳️ Falsy 值:假得悄无声息

以下值在布尔上下文中为 false

false
0
""
null
undefined
NaN

其他值一律为真:

if ("false") console.log("字符串 false 也是真的");
if ([]) console.log("空数组也是真的");
if ({}) console.log("空对象也是真的");

🧠 练习题

typeof undefined; // "undefined"
typeof null; // "object"
typeof NaN; // "number"
typeof []; // "object"
typeof {}; // "object"
typeof (() => {});// "function"

🧰 判断数组的正确姿势

Array.isArray([]);      // true
[] instanceof Array; // true
typeof [] === "object"; // true,但不够精准

🧩 小测验

  1. 以下代码输出什么?
let a = "123";
console.log(typeof a === "number"); // false
  1. 哪些值会被当成 false
  • B. 0
  • C. ""
  • E. null

🧯 小结

类型特点判断方法
原始类型不可变,值传递typeof
对象类型可变,引用传递typeof / instanceof
null 的坑typeof null === object历史 bug
判断数组特殊对象Array.isArray(arr)