Variables — let and const · 变量 —— let 与 const
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version. · 此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
English
A variable is a named box
- A variable stores a value and gives it a name, so you can use it again later.
letmakes a box you can change.constmakes a box that must stay the same (a constant).
中文
变量是一个有名字的盒子
- 变量(variable)存放一个值,并给它一个名字,这样你之后可以再次使用它。
let创建一个可以修改的盒子。const创建一个必须保持不变的盒子(常量,constant)。
let age = 15; // a value that may change
const name = "Ada"; // a value that won't
console.log(name, age); // → Ada 15
English
Change a let with a new value
- Assign again —
count = count + 1— to update alet. count++is a handy shortcut for "add 1 tocount".
中文
用新值修改一个 let
- 再次赋值 ——
count = count + 1—— 就能更新一个let。 count++是 “给count加 1” 的便捷写法。
let count = 0;
count = count + 1;
count++;
console.log(count); // → 2
Explore · 探索
Watch the boxes change · 看着盒子变化
A variable is a named box. let can be changed; const stays fixed. · 变量就是一个有名字的盒子。let 可以修改;const 保持不变。
English
Watch out
- A
constcannot be reassigned:const x = 1; x = 2;throws an error. - Good habit: use
constby default, and reach forletonly when the value truly changes.
中文
注意
const不能被重新赋值:const x = 1; x = 2;会抛出错误。- 好习惯:默认用
const,只有当值确实会变时才用let。
English
Common mistakes
- Use
constfor values that never change,letfor those that do. - Declare a variable before you use it.
中文
常见错误
- 不变的值用
const,会变的用let。 - 先声明变量再使用。
English
Now you try
- Use
letorconstto store values. - Press Check answer to test it.
中文
现在轮到你
- 用
let或const存放值。 - 按检查答案来测试它。
Store the text Cairo in a const called · 称为 city, then log city. · 把文本 Cairo 存进一个名为 city 的 const,然后打印 city。
Click Run to see the output here. · 点击“运行”查看此处输出。
let w = 4 and let h = 3 are the width and height. Work out the area (w * h) and log it (it is 12). · let w = 4、let h = 3 是宽和高。算出面积(w * h)并打印(是 12)。
Click Run to see the output here. · 点击“运行”查看此处输出。
Make a let total = 10, add 5 to it, then log total (it is 15). · 创建 let total = 10,给它加 5,然后打印 total(是 15)。
Click Run to see the output here. · 点击“运行”查看此处输出。