官术网_书友最值得收藏!

Variables

Variables are used to store data. When writing programs, it is convenient to use variables instead of the actual data, as it's much easier to write pi instead of 3.141592653589793 especially when it happens several times inside your program. The data stored in a variable can be changed after it was initially assigned, hence the name "variable". Variables are also useful for storing data that is unknown to the programmer when the code is written, such as the result of later operations.

There are two steps required in order to use a variable. You need to:

  • Declare the variable
  • Initialize it, that is, give it a value

In order to declare a variable, you use the var statement, like this:

var a; 
var thisIsAVariable; 
var _and_this_too; 
var mix12three;

For the names of the variables, you can use any combination of letters, numbers, and the underscore character. However, you can't start with a number, which means that this is invalid:

var 2three4five;

To initialize a variable means to give it a value for the first (initial) time. You have two ways to do so:

  • Declare the variable first, then initialize it, or
  • Declare and initialize with a single statement

An example of the latter is:

var a = 1;

Now the variable named a contains the value 1.

You can declare (and optionally initialize) several variables with a single var statement; just separate the declarations with a comma:

var v1, v2, v3 = 'hello', v4 = 4, v5;

Variables are Case Sensitive

Variable names are case-sensitive. You can verify this statement using the Firebug console. Try typing this, pressing Enter after each line:

var case_matters = 'lower';
var CASE_MATTERS = 'upper';
case_matters
CASE_MATTERS

To save keystrokes, when you enter the third line, you can only type ca and press the Tab key. The console will auto-complete the variable name to case_matters. Similarly, for the last line—type CA and press Tab. The end result is shown on the following figure.

Variables are Case Sensitive

Throughout the rest of this book, only the code for the examples will be given, instead of a screenshot:

>>> var case_matters = 'lower';
>>> var CASE_MATTERS = 'upper';
>>> case_matters

"lower"

>>> CASE_MATTERS

"upper"

The three consecutive greater-than signs (>>>) show the code that you type, the rest is the result, as printed in the console. Again, remember that when you see such code examples, you're strongly encouraged to type in the code yourself and experiment tweaking it a little here and there, so that you get a better feeling of how it works exactly.

主站蜘蛛池模板: 遂平县| 上栗县| 田阳县| 东源县| 山东省| 缙云县| 竹北市| 遂溪县| 康定县| 高唐县| 曲周县| 颍上县| 黎城县| 永兴县| 洛隆县| 肇庆市| 桐柏县| 嘉善县| 武定县| 嘉善县| 抚宁县| 庐江县| 旬邑县| 阿拉善盟| 武乡县| 石柱| 连云港市| 磴口县| 孟州市| 河间市| 柳江县| 罗平县| 麻阳| 景德镇市| 博乐市| 运城市| 安国市| 越西县| 荔浦县| 蕲春县| 津市市|