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

  • Object/Oriented JavaScript
  • Stoyan Stefanov
  • 427字
  • 2021-08-13 19:25:51

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.

主站蜘蛛池模板: 襄汾县| 淮南市| 张家界市| 拉萨市| 涟源市| 财经| 衡南县| 福海县| 卢龙县| 陆河县| 广安市| 柳州市| 金阳县| 巴楚县| 乌兰浩特市| 余江县| 兴国县| 漳平市| 崇礼县| 利辛县| 浪卡子县| 勐海县| 宣恩县| 天长市| 颍上县| 长海县| 吉林省| 红桥区| 永善县| 安阳市| 祁门县| 平谷区| 万州区| 兴国县| 清苑县| 德保县| 诸暨市| 武邑县| 潼南县| 隆尧县| 仁化县|