var Statement
Declares a variable.
语法
var variable1 = value1
参数
variable1
The name of the variable being declared.
value1
The initial value assigned to the variable.
备注
Use the var
statement to declare variables. You can assign values to the variables when you declare them or later in your script.
A variable is declared the first time it appears in your script.
You can declare a variable without using the var
keyword and assign a value to it. This is known as an implicit declaration, and it is not recommended. An implicit declaration gives the variable global scope. When you declare a variable at the procedure level, though, you typically do not want it to have global scope. To avoid giving the variable global scope, you must use the var
keyword in your variable declaration.
If you do not initialize your variable in the var
statement, it is automatically assigned the JavaScript value undefined
.
示例
The following examples illustrate the use of the var
statement.
var index; var name = "Thomas Jefferson"; var answer = 42, counter, numpages = 10; var myarray = new Array();
必备条件
在以下文档模式中受支持:怪异模式、Internet Explorer 6标准模式、Internet Explorer 7标准模式、Internet Explorer 8标准模式、Internet Explorer 9标准模式、Internet Explorer 10标准模式、Internet Explorer 11标准模式。应用商店应用(Windows 8和Windows Phone 8.1)中也受支持。请参阅版本信息。