存储你需要的信息 - 变量

阅读完最后几篇文章后,你现在应该了解 JavaScript 是什么、它可以为你做什么、如何将它与其他 Web 技术一起使用,以及从高层次来看它的主要功能是什么样的。在本文中,我们将深入了解真正的基础知识,了解如何使用 JavaScript 最基本的构建块 - 变量。

¥After reading the last couple of articles you should now know what JavaScript is, what it can do for you, how you use it alongside other web technologies, and what its main features look like from a high level. In this article, we will get down to the real basics, looking at how to work with the most basic building blocks of JavaScript — Variables.

先决条件: 对 HTML 和 CSS 有基本的了解,对 JavaScript 有了解。
目标: 熟悉 JavaScript 变量的基础知识。

你需要的工具

¥Tools you need

在本文中,你将被要求输入几行代码来测试你对内容的理解。如果你使用的是桌面浏览器,则键入示例代码的最佳位置是浏览器的 JavaScript 控制台(有关如何访问此工具的更多信息,请参阅 什么是浏览器开发工具)。

¥Throughout this article, you'll be asked to type in lines of code to test your understanding of the content. If you are using a desktop browser, the best place to type your sample code is your browser's JavaScript console (see What are browser developer tools for more information on how to access this tool).

什么是变量?

¥What is a variable?

变量是值的容器,就像我们可能在求和中使用的数字,或者我们可能用作句子一部分的字符串。

¥A variable is a container for a value, like a number we might use in a sum, or a string that we might use as part of a sentence.

变量示例

¥Variable example

让我们看一个例子:

¥Let's look at an example:

html
<button id="button_A">Press me</button>
<h3 id="heading_A"></h3>
js
const buttonA = document.querySelector("#button_A");
const headingA = document.querySelector("#heading_A");

let count = 1;

buttonA.onclick = () => {
  buttonA.textContent = "Try again!";
  headingA.textContent = `${count} clicks so far`;
  count += 1;
};

在此示例中,按下按钮会运行一些代码。首先,它会更改按钮本身上的文本。其次,它会显示一条消息,显示按钮被按下的次数。该数字存储在变量中。每次用户按下按钮时,变量中的数字都会增加一。

¥In this example pressing the button runs some code. First, it changes the text on the button itself. Second, it shows a message of the number of times the button has been pressed. The number is stored in a variable. Each time the user presses the button, the number in the variable will increment by one.

没有变量

¥Without a variable

为了理解为什么这如此有用,让我们考虑一下如何在不使用变量的情况下编写这个示例。它最终会看起来像这样:

¥To understand why this is so useful, let's think about how we'd write this example without using a variable. It would end up looking something like this:

html
<button id="button_B">Press me</button>
<h3 id="heading_B"></h3>
js
const buttonB = document.querySelector("#button_B");
const headingB = document.querySelector("#heading_B");

buttonB.onclick = () => {
  buttonB.textContent = "Try again!";
  headingB.textContent = "1 click so far";
};

你可能不完全理解我们正在使用的语法(还!),但你应该能够理解。如果没有变量,我们就无法知道按钮被点击了多少次。当无法记住任何信息时,发送给用户的消息很快就会变得无关紧要。

¥You may not fully understand the syntax we are using (yet!), but you should be able to get the idea. Without a variable, we don't have a way of knowing how many times the button have been clicked. The message to the user will quickly be irrelevant when no information can be remembered.

变量是有意义的,随着你对 JavaScript 的了解越来越多,它们将开始成为第二天性。

¥Variables just make sense, and as you learn more about JavaScript they will start to become second nature.

变量的一个特殊之处在于它们几乎可以包含任何内容 - 而不仅仅是字符串和数字。变量还可以包含复杂的数据甚至整个函数来完成令人惊奇的事情。随着你的继续,你将了解更多相关信息。

¥One special thing about variables is that they can contain just about anything — not just strings and numbers. Variables can also contain complex data and even entire functions to do amazing things. You'll learn more about this as you go along.

注意:我们说变量包含值。这是一个重要的区别。变量不是值本身,而是值。它们是价值观的容器。你可以将它们想象成可以存放东西的小纸板箱。

¥Note: We say variables contain values. This is an important distinction to make. Variables aren't the values themselves; they are containers for values. You can think of them being like little cardboard boxes that you can store things in.

A screenshot of three 3-dimensional cardboard boxes demonstrating examples of JavaScript variables. Each box contains hypothetical values that represent various JavaScript data types. The sample values are "Bob", true and 35 respectively.

声明一个变量

¥Declaring a variable

要使用变量,你首先必须创建它 - 更准确地说,我们称之为声明变量。为此,我们键入关键字 let,后跟要调用变量的名称:

¥To use a variable, you've first got to create it — more accurately, we call this declaring the variable. To do this, we type the keyword let followed by the name you want to call your variable:

js
let myName;
let myAge;

这里我们创建两个变量,名为 myNamemyAge。尝试在网络浏览器的控制台中输入这些行。之后,尝试使用你自己选择的名称创建一个(或两个)变量。

¥Here we're creating two variables called myName and myAge. Try typing these lines into your web browser's console. After that, try creating a variable (or two) with your own name choices.

注意:在 JavaScript 中,所有代码指令都应以分号 (;) 结尾 — 你的代码对于单行代码可能可以正常工作,但当你一起编写多行代码时可能无法正常工作。尝试养成包含它的习惯。

¥Note: In JavaScript, all code instructions should end with a semicolon (;) — your code may work correctly for single lines, but probably won't when you are writing multiple lines of code together. Try to get into the habit of including it.

你可以通过仅键入变量名称来测试这些值现在是否存在于执行环境中,例如

¥You can test whether these values now exist in the execution environment by typing just the variable's name, e.g.

js
myName;
myAge;

它们目前没有任何价值;它们是空容器。当你输入变量名称时,你应该得到返回值 undefined。如果它们不存在,你将收到一条错误消息 - 尝试输入

¥They currently have no value; they are empty containers. When you enter the variable names, you should get a value of undefined returned. If they don't exist, you'll get an error message — try typing in

js
scoobyDoo;

注意:不要将存在但没有定义值的变量与根本不存在的变量混淆 - 它们是非常不同的东西。在上面看到的盒子类比中,不存在意味着没有可供输入值的盒子(变量)。没有定义值意味着有一个盒子,但里面没有值。

¥Note: Don't confuse a variable that exists but has no defined value with a variable that doesn't exist at all — they are very different things. In the box analogy you saw above, not existing would mean there's no box (variable) for a value to go in. No value defined would mean that there is a box, but it has no value inside it.

初始化变量

¥Initializing a variable

声明变量后,你可以使用值对其进行初始化。你可以通过键入变量名称、后跟等号 (=) 和要为其指定的值来执行此操作。例如:

¥Once you've declared a variable, you can initialize it with a value. You do this by typing the variable name, followed by an equals sign (=), followed by the value you want to give it. For example:

js
myName = "Chris";
myAge = 37;

现在尝试返回控制台并输入这些行。在每种情况下,你应该在控制台中看到你分配给返回的变量的值以进行确认。同样,你可以通过在控制台中输入变量名称来返回变量值 - 再试一次:

¥Try going back to the console now and typing in these lines. You should see the value you've assigned to the variable returned in the console to confirm it, in each case. Again, you can return your variable values by typing their name into the console — try these again:

js
myName;
myAge;

你可以同时声明和初始化变量,如下所示:

¥You can declare and initialize a variable at the same time, like this:

js
let myDog = "Rover";

这可能是你大多数时候都会做的事情,因为它比在两条单独的行上执行这两个操作更快。

¥This is probably what you'll do most of the time, as it is quicker than doing the two actions on two separate lines.

关于 var 的注释

¥A note about var

你可能还会看到使用 var 关键字声明变量的不同方式:

¥You'll probably also see a different way to declare variables, using the var keyword:

js
var myName;
var myAge;

当 JavaScript 最初创建时,这是声明变量的唯一方法。var 的设计混乱且容易出错。因此,let 是在现代版本的 JavaScript 中创建的,这是一个用于创建变量的新关键字,其工作方式与 var 有所不同,解决了该过程中的问题。

¥Back when JavaScript was first created, this was the only way to declare variables. The design of var is confusing and error-prone. So let was created in modern versions of JavaScript, a new keyword for creating variables that works somewhat differently to var, fixing its issues in the process.

下面解释了几个简单的差异。我们现在不会讨论所有差异,但是当你了解有关 JavaScript 的更多信息时,你将开始发现它们(如果你现在确实想了解它们,请随时查看我们的 让参考页面)。

¥A couple of simple differences are explained below. We won't go into all the differences now, but you'll start to discover them as you learn more about JavaScript (if you really want to read about them now, feel free to check out our let reference page).

首先,如果你编写一个声明并初始化变量的多行 JavaScript 程序,那么你实际上可以在初始化变量后使用 var 声明变量,并且它仍然可以工作。例如:

¥For a start, if you write a multiline JavaScript program that declares and initializes a variable, you can actually declare a variable with var after you initialize it and it will still work. For example:

js
myName = "Chris";

function logName() {
  console.log(myName);
}

logName();

var myName;

注意:当在 JavaScript 控制台中输入单独的行时,或者在 Web 文档中运行多行 JavaScript 时,这将不起作用。

¥Note: This won't work when typing individual lines into a JavaScript console, just when running multiple lines of JavaScript in a web document.

这是由于提升而起作用的 - 请阅读 无功提升 以获取有关该主题的更多详细信息。

¥This works because of hoisting — read var hoisting for more detail on the subject.

提升不再适用于 let。如果我们在上例中将 var 更改为 let,则会失败并出现错误。这是一件好事 - 在初始化变量后声明它会导致代码混乱、难以理解。

¥Hoisting no longer works with let. If we changed var to let in the above example, it would fail with an error. This is a good thing — declaring a variable after you initialize it results in confusing, harder to understand code.

其次,当你使用 var 时,你可以多次声明同一个变量,但使用 let 则不能。以下内容将起作用:

¥Secondly, when you use var, you can declare the same variable as many times as you like, but with let you can't. The following would work:

js
var myName = "Chris";
var myName = "Bob";

但是下面的代码会在第二行抛出错误:

¥But the following would throw an error on the second line:

js
let myName = "Chris";
let myName = "Bob";

你必须这样做:

¥You'd have to do this instead:

js
let myName = "Chris";
myName = "Bob";

同样,这是一个明智的语言决定。没有理由重新声明变量 - 它只会让事情变得更加混乱。

¥Again, this is a sensible language decision. There is no reason to redeclare variables — it just makes things more confusing.

出于这些原因以及更多原因,我们建议你在代码中使用 let,而不是 var。除非你明确编写对古代浏览器的支持,否则没有任何理由使用 var,因为自 2015 年以来所有现代浏览器都支持 let

¥For these reasons and more, we recommend that you use let in your code, rather than var. Unless you are explicitly writing support for ancient browsers, there is no longer any reason to use var as all modern browsers have supported let since 2015.

注意:如果你在浏览器的控制台中尝试此代码,最好将每个代码块作为一个整体复制并粘贴到此处。有一个 Chrome 控制台中的功能,其中允许使用 letconst 重新声明变量:

¥Note: If you are trying this code in your browser's console, prefer to copy & paste each of the code blocks here as a whole. There's a feature in Chrome's console where variable re-declarations with let and const are allowed:

> let myName = "Chris";
  let myName = "Bob";
// As one input: SyntaxError: Identifier 'myName' has already been declared

> let myName = "Chris";
> let myName = "Bob";
// As two inputs: both succeed

更新变量

¥Updating a variable

使用值初始化变量后,你可以通过为其指定不同的值来更改(或更新)该值。尝试在控制台中输入以下几行:

¥Once a variable has been initialized with a value, you can change (or update) that value by giving it a different value. Try entering the following lines into your console:

js
myName = "Bob";
myAge = 40;

关于变量命名规则的旁白

¥An aside on variable naming rules

你几乎可以将变量称为任何你喜欢的名称,但也有一些限制。一般来说,你应该坚持只使用拉丁字符(0-9、a-z、A-Z)和下划线字符。

¥You can call a variable pretty much anything you like, but there are limitations. Generally, you should stick to just using Latin characters (0-9, a-z, A-Z) and the underscore character.

  • 你不应使用其他字符,因为它们可能会导致错误或难以让国际观众理解。
  • 不要在变量名的开头使用下划线 - 这在某些 JavaScript 结构中用于表示特定的事物,因此可能会造成混淆。
  • 不要在变量的开头使用数字。这是不允许的,并且会导致错误。
  • 一个安全的约定是遵守 lower camel case,即将多个单词组合在一起,第一个单词全部小写,然后将后续单词大写。到目前为止,我们一直在文章中使用它作为变量名称。
  • 使变量名称直观,以便它们描述它们包含的数据。不要只使用单个字母/数字或长短语。
  • 变量区分大小写 — 因此 myage 是与 myAge 不同的变量。
  • 最后一点:你还需要避免使用 JavaScript 保留字作为变量名 - 我们指的是构成 JavaScript 实际语法的单词!因此,不能使用 varfunctionletfor 等单词作为变量名。浏览器将它们识别为不同的代码项,因此你会收到错误。

注意:你可以在 词汇语法 - 关键词 找到要避免的保留关键字的相当完整的列表。

¥Note: You can find a fairly complete list of reserved keywords to avoid at Lexical grammar — keywords.

好名字的例子:

¥Good name examples:

age
myAge
init
initialColor
finalOutputValue
audio1
audio2

不良名称示例:

¥Bad name examples:

1
a
_12
myage
MYAGE
var
Document
skjfndskjfnbdskjfb
thisisareallylongvariablenameman

牢记上述指导,现在尝试创建更多变量。

¥Try creating a few more variables now, with the above guidance in mind.

变量类型

¥Variable types

我们可以在变量中存储几种不同类型的数据。在本节中,我们将简要描述这些内容,然后在以后的文章中,你将更详细地了解它们。

¥There are a few different types of data we can store in variables. In this section we'll describe these in brief, then in future articles, you'll learn about them in more detail.

数字

¥Numbers

你可以在变量中存储数字,可以是整数,如 30(也称为整数),也可以是小数,如 2.456(也称为浮点数或浮点数)。与其他一些编程语言不同,你不需要在 JavaScript 中声明变量类型。当你为变量指定数值时,不包含引号:

¥You can store numbers in variables, either whole numbers like 30 (also called integers) or decimal numbers like 2.456 (also called floats or floating point numbers). You don't need to declare variable types in JavaScript, unlike some other programming languages. When you give a variable a number value, you don't include quotes:

js
let myAge = 17;

字符串

¥Strings

字符串是文本片段。当给变量赋予字符串值时,需要将其用单引号或双引号括起来;否则,JavaScript 会尝试将其解释为另一个变量名。

¥Strings are pieces of text. When you give a variable a string value, you need to wrap it in single or double quote marks; otherwise, JavaScript tries to interpret it as another variable name.

js
let dolphinGoodbye = "So long and thanks for all the fish";

布尔值

¥Booleans

布尔值是真/假值 - 它们可以有两个值,truefalse。这些通常用于测试条件,然后根据情况运行代码。例如,一个简单的情况是:

¥Booleans are true/false values — they can have two values, true or false. These are generally used to test a condition, after which code is run as appropriate. So for example, a simple case would be:

js
let iAmAlive = true;

而实际上它的使用方式更像是这样的:

¥Whereas in reality it would be used more like this:

js
let test = 6 < 3;

这是使用 "少于" 运算符 (<) 来测试 6 是否小于 3。正如你所料,它返回 false,因为 6 不小于 3!稍后你将在课程中了解有关此类运算符的更多信息。

¥This is using the "less than" operator (<) to test whether 6 is less than 3. As you might expect, it returns false, because 6 is not less than 3! You will learn a lot more about such operators later on in the course.

数组

¥Arrays

数组是一个包含多个值的单个对象,这些值括在方括号中并用逗号分隔。尝试在控制台中输入以下几行:

¥An array is a single object that contains multiple values enclosed in square brackets and separated by commas. Try entering the following lines into your console:

js
let myNameArray = ["Chris", "Bob", "Jim"];
let myNumberArray = [10, 15, 40];

定义这些数组后,你可以通过数组中的位置访问每个值。尝试这些行:

¥Once these arrays are defined, you can access each value by their location within the array. Try these lines:

js
myNameArray[0]; // should return 'Chris'
myNumberArray[2]; // should return 40

方括号指定与要返回的值的位置相对应的索引值。你可能已经注意到 JavaScript 中的数组是零索引的:第一个元素位于索引 0 处。

¥The square brackets specify an index value corresponding to the position of the value you want returned. You might have noticed that arrays in JavaScript are zero-indexed: the first element is at index 0.

要了解更多信息,请参阅我们关于 数组 的文章。

¥To learn more, see our article on Arrays.

对象

¥Objects

在编程中,对象是模拟现实生活中对象的代码结构。你可以有一个代表一个盒子的简单对象,并包含有关其宽度、长度和高度的信息,或者你可以有一个代表一个人的对象,并包含有关其名称、身高、体重、他们所说的语言、如何使用的数据。 向他们打招呼等等。

¥In programming, an object is a structure of code that models a real-life object. You can have a simple object that represents a box and contains information about its width, length, and height, or you could have an object that represents a person, and contains data about their name, height, weight, what language they speak, how to say hello to them, and more.

尝试在控制台中输入以下行:

¥Try entering the following line into your console:

js
let dog = { name: "Spot", breed: "Dalmatian" };

要检索存储在对象中的信息,可以使用以下语法:

¥To retrieve the information stored in the object, you can use the following syntax:

js
dog.name;

有关此主题的更多信息,请参阅 JavaScript 对象介绍 模块。

¥For more on this topic, see the Introducing JavaScript objects module.

动态类型

¥Dynamic typing

JavaScript 是 "动态类型语言",这意味着与其他一些语言不同,你不需要指定变量将包含什么数据类型(数字、字符串、数组等)。

¥JavaScript is a "dynamically typed language", which means that, unlike some other languages, you don't need to specify what data type a variable will contain (numbers, strings, arrays, etc.).

例如,如果你声明一个变量并为其指定一个用引号引起来的值,则浏览器会将该变量视为字符串:

¥For example, if you declare a variable and give it a value enclosed in quotes, the browser treats the variable as a string:

js
let myString = "Hello";

即使引号括起来的值只是数字,它仍然是一个字符串 - 而不是数字 - 所以要小心:

¥Even if the value enclosed in quotes is just digits, it is still a string — not a number — so be careful:

js
let myNumber = "500"; // oops, this is still a string
typeof myNumber;
myNumber = 500; // much better — now this is a number
typeof myNumber;

尝试将上面的四行逐一输入到控制台中,看看结果是什么。你会注意到我们使用了一个名为 typeof 的特殊运算符 - 它返回你在其后键入的变量的数据类型。第一次调用它时,它应该返回 string,因为此时 myNumber 变量包含一个字符串 '500'。看看第二次调用它时它会返回什么。

¥Try entering the four lines above into your console one by one, and see what the results are. You'll notice that we are using a special operator called typeof — this returns the data type of the variable you type after it. The first time it is called, it should return string, as at that point the myNumber variable contains a string, '500'. Have a look and see what it returns the second time you call it.

JavaScript 中的常量

¥Constants in JavaScript

除了变量之外,你还可以声明常量。这些类似于变量,不同之处在于:

¥As well as variables, you can declare constants. These are like variables, except that:

  • 声明它们时必须初始化它们
  • 初始化它们后,你无法为它们分配新值。

例如,使用 let 你可以声明一个变量而不对其进行初始化:

¥For example, using let you can declare a variable without initializing it:

js
let count;

如果你尝试使用 const 执行此操作,你将看到错误:

¥If you try to do this using const you will see an error:

js
const count;

同样,使用 let,你可以初始化一个变量,然后为其分配一个新值(这也称为重新分配变量):

¥Similarly, with let you can initialize a variable, and then assign it a new value (this is also called reassigning the variable):

js
let count = 1;
count = 2;

如果你尝试使用 const 执行此操作,你将看到错误:

¥If you try to do this using const you will see an error:

js
const count = 1;
count = 2;

请注意,尽管 JavaScript 中的常量必须始终命名相同的值,但你可以更改其命名的值的内容。对于数字或布尔值等简单类型来说,这不是一个有用的区别,但请考虑一个对象:

¥Note that although a constant in JavaScript must always name the same value, you can change the content of the value that it names. This isn't a useful distinction for simple types like numbers or booleans, but consider an object:

js
const bird = { species: "Kestrel" };
console.log(bird.species); // "Kestrel"

你可以更新、添加或删除使用 const 声明的对象的属性,因为即使对象的内容已更改,常量仍然指向同一个对象:

¥You can update, add, or remove properties of an object declared using const, because even though the content of the object has changed, the constant is still pointing to the same object:

js
bird.species = "Striated Caracara";
console.log(bird.species); // "Striated Caracara"

何时使用 const,何时使用 let

¥When to use const and when to use let

如果你用 const 做的事情不如用 let 做的那么多,为什么你更愿意使用它而不是 let?事实上 const 非常有用。如果你使用 const 来命名一个值,它会告诉任何查看你代码的人该名称永远不会分配给不同的值。每当他们看到这个名字时,他们就会知道它指的是什么。

¥If you can't do as much with const as you can with let, why would you prefer to use it rather than let? In fact const is very useful. If you use const to name a value, it tells anyone looking at your code that this name will never be assigned to a different value. Any time they see this name, they will know what it refers to.

在本课程中,我们对于何时使用 let、何时使用 const 采用以下原则:

¥In this course, we adopt the following principle about when to use let and when to use const:

可以时使用 const,必要时使用 let

¥Use const when you can, and use let when you have to.

这意味着,如果你可以在声明变量时对其进行初始化,并且以后不需要重新分配它,请将其设为常量。

¥This means that if you can initialize a variable when you declare it, and don't need to reassign it later, make it a constant.

测试你的技能!

¥Test your skills!

你已读完本文,但你还记得最重要的信息吗?在继续之前,你可以找到一些进一步的测试来验证你是否已保留此信息 - 请参阅 测试你的技能:variables

¥You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on — see Test your skills: variables.

概括

¥Summary

到目前为止,你应该对 JavaScript 变量以及如何创建它们有一定的了解。在下一篇文章中,我们将更详细地关注数字,了解如何在 JavaScript 中进行基本数学运算。

¥By now you should know a reasonable amount about JavaScript variables and how to create them. In the next article, we'll focus on numbers in more detail, looking at how to do basic math in JavaScript.