如何存储你需要的信息 — 变量


在读完之前的一些文章之后,你现在应该大概知道了JavaScript是什么,你能用它干什么,它是怎么跟其他web技术(HTML,CSS)协同工作的,以及它有哪些主要特性。在本章节,我们将开始学习JavaScript的基础,了解如何使用 -- 变量。

预备知识: 电脑基础知识,了解基本的 HTML 和 CSS,了解JavaScript是什么。
目标: 熟悉JavaScript的变量使用


在本章中,你将要输入一些代码来测试你对相关内容的理解。如果你是用的桌面浏览器,输入这些代码最好的地方是浏览器的JavaScript终端,(参考 What are browser developer tools 查看如何使用这些工具)。




<button>Press me</button>
var button = document.querySelector('button');

button.onclick = function() {
  var name = prompt('What is your name?');
  alert('Hello ' + name + ', nice to see you!');



var name = prompt('What is your name?');

if (name === 'Adam') {
  alert('Hello Adam, nice to see you!');
} else if (name === 'Alan') {
  alert('Hello Alan, nice to see you!');
} else if (name === 'Bella') {
  alert('Hello Bella, nice to see you!');
} else if (name === 'Bianca') {
  alert('Hello Bianca, nice to see you!');
} else if (name === 'Chris') {
  alert('Hello Chris, nice to see you!');

// ... and so on ...

你可能暂时还没有完全理解这些代码和语法,但是你应该能够理解到 -- 如果我们没有变量,我们就不得不写大量的代码去枚举和检查输入的名字,然后去显示它们。这样做显然是低效率和不可行的 -- 你没有办法列举出所有可能的输入。

变量的另一个特性就是它们能够存储任何的东西 -- 不只是字符串和数字。变量可以存储更复杂的数据,甚至是函数。你将在后续的内容中体验到这些用法。



要想使用变量,你需要做的第一步就是创建它 -- 更准确的说,是声明一个变量。声明一个变量的语法是在var关键字之后加上这个变量的名字:

var myName;
var myAge;

在这里我们声明了两个变量 myNamemyAge. 那么现在尝试输入这些代码到你的浏览器终端或者下面提供的JavaScript终端 (你也可以在另一个独立的标签页或窗口 open this consol ). 此外,你也可以多声明几个变量.

提示: 在JavaScript中,所有代码指令都会以分号结尾 (;) — 如果忘记加分号,你的单行代码可能执行正常,但是在多行代码在一起的时候就可能出错。所以,最好是养成主动以分号作为代码结尾的习惯。





提示: 千万不要把两个概念弄混淆了,“一个变量存在,但是没有数值”和“一个变量并不存在” — 他们完全是两回事.


一旦你定义了一个变量,你就能够初始化它. 方法如下,在变量名之后跟上一个“=”,然后是数值:

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 simply typing their name into the console — try these again:


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

var myName = 'Chris';

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

Note: If you write a multiline JavaScript program that declares and initializes a variable, you can actually declare it after you initialize it and it will still work. This is because variable declarations are generally done first before the rest of the code is executed. This is called hoisting — read var hoisting for more detail on the subject.

Updating a variable

Once a variable has had a value assigned, you can update that value by simply giving it a different value. Try entering the following lines into your console:

myName = 'Bob';
myAge = 40;

An aside on variable naming rules

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.

  • You shouldn't use other characters because they may cause errors or be hard to understand by an international audience.
  • Don't use underscores at the start of variable names — this is used in certain JavaScript constructs to mean specific things, so may get confusing.
  • Don't use numbers at the start of variables. This isn't allowed and will cause an error.
  • A safe convention to stick to is so-called "lower camel case", where you stick together multiple words, using lower case for the whole first word and then capitalize subsequent words. We've been using this for our variable names in the article so far.
  • Make variable names intuitive, so they describe the data they contain. Don't just use single letters/numbers, or big long phrases.
  • Variables are case sensitive — so myage is a different variable to myAge.
  • One last point — you also need to avoid using JavaScript reserved words as your variable names — by this, we mean the words that make up the actual syntax of JavaScript! So you can't use words like var, function, let, and for as variable names. Browsers will recognize them as different code items, and so you'll get errors.

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

Good name examples:


Bad name examples:


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 (data types). In this section we'll describe these in brief, then in future articles you'll learn about them in more detail.

So far we've looked at the first two, but there are others.


You can store numbers in variables, be those whole numbers like 30 (also called integers) or decimal numbers like 2.456 (also called floats or floating point numbers). JavaScript doesn't have different data types for different number types, like some programming languages do. When you give a variable a number value, you don't include quotes:

var myAge = 17;


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 will try to intepret it as another variable name.

var dolphinGoodbye = 'So long and thanks for all the fish';


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:

var iAmAlive = true;

Whereas in reality it would be used more like this:

var test = 6 < 3;

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


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:

var myNameArray = ['Chris', 'Bob', 'Jim'];
var myNumberArray = [10,15,40];

Once these arrays are defined, you can access their individual values using syntax like the following. Try these lines:

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

The square brackets here contain an index value that specifies the position of the value you want returned. You might have noticed that computers count from 0, instead of 1 like us humans do.

You'll learn a lot more about arrays in a future article.


In programming, an object is a structure of code that models a real life object. You can have a simple object that represents a car park and contains information about its width and length, 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 you console:

var dog = { name : 'Spot', breed : 'Dalmatian' };

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


We won't be looking at objects any more for now — you can learn more about those in a future module.

Loose typing

JavaScript is a "loosely typed language", which means that, unlike some other languages, you don't need to specify what data type a variable will contain (e.g. number? string?).

For example if you declare a variable and give it a value with quotes round it, the browser will know it is a string:

var myString = 'Hello';

It will still be a string, even if it contains numbers, so be careful:

var myNumber = '500'; // oops, this is still a string
myNumber = 500; // much better — now this is a number

Try entering the four lines above into your console one by one, and see what the results are (don't type in the comments). You'll notice that we are using a special function called typeof() — this returns the data type of the variable you pass to it. The first time it is called in the above sequence, 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.


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.


 此页面的贡献者: Lawson.Yuan
 最后编辑者: Lawson.Yuan,