数据类型
理解字符串, 数字, 布尔值, and 更多 — 基本 kinds 的数据每个 program 工作使用.
你将学到
- 什么数据类型是 and 为什么它 matters
- 核心 primitive 类型: 字符串, 数字, 布尔值
- 如何空 and undefined represent '否值'
- difference 之间 primitive and composite 类型
概念讲解
数据类型
A data type is a category of data. It tells the computer what kind of value is stored and what operations make sense. You can multiply two numbers, but you cannot multiply "apple" by "orange" — the types determine what is valid.
The Core Primitives
JavaScript has a handful of primitive types — single, indivisible values:
| Type | Example | Meaning | |------|---------|---------| | String | "hello" | Text, wrapped in quotes | | Number | 42, 3.14 | Integers and decimals | | Boolean | 真, 假 | Exactly two values | | null | 空 | Intentional "否值" | | undefined | undefined | A variable with no value yet |
Strings
A string is text. Use single or double quotes, or backticks for template literals that allow interpolation:
const name = "Ada";
const greeting = `Hello, ${name}!`; // "Hello, Ada!"
Booleans
A boolean is a true/false flag. They are the output of comparisons (5 > 3 is 真) and the input of 如果 statements. Booleans are how programs make decisions.
Primitives vs. Composites
Primitives (string, number, boolean) hold a single value. Composite types — arrays and objects — hold many values together. You will meet them in later lessons. The distinction matters: primitives are copied by value, composites by reference, which affects how they behave when you assign them.
示例代码
const text = "Hello"; // string
const count = 42; // number
const isActive = true; // boolean
const empty = null; // intentional empty
let notAssigned; // undefined
// The typeof operator reveals a value's type:
console.log(typeof text); // "string"
console.log(typeof count); // "number"
console.log(typeof isActive); // "boolean"
console.log(typeof empty); // "object" (a famous JS quirk!)
console.log(typeof notAssigned); // "undefined"
// Operations depend on type:
console.log(10 + 5); // 15 (number + number)
console.log("10" + "5"); // "105" (string + string = concatenation!)
Notice 如何 + behaves differently for 数字对比. 字符串. 这个是 为什么 knowing 类型 matters — 相同运算符能 做不同 things.
动手试一试
- JSON Formatter
JSON 是构建从 字符串, 数字, 布尔值, 空, 数组, and 对象. 粘贴数据 and identify 每个类型.
常见错误
错误写法
添加数字到 字符串 and expecting numeric addition.
正确做法
Use 数字() or parseInt() 到 convert 字符串首先: 数字('5') + 5 gives 10, 不 '55'.
错误写法
Confusing 空使用 undefined.
正确做法
Use 空当 你 intentionally 设置 '否值'. undefined 平均值变量是 从不 assigned. 它们是 不同.
相关资源
相关代码片段
- JavaScript 数组方法
Composite 类型 in 操作 — 数组持有许多输入值.
练习 数据类型
15 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。