Javascript 简明教程
JavaScript - var Keyword
var 关键字在 JavaScript 中用来声明变量。在 ES6 之前,只有 var 关键字可以声明变量。在 ES6 中,let 和 const 关键字被引入作为声明变量的更好方法。建议使用 let 而不是 var 来声明变量。如果你针对的是旧版本浏览器,你可以使用 var。
The var keyword in JavaScript is used to declare variables. Before ES6, there was only var keyword to declare a variable. In ES6, let and const keywords were introduced as a better way to declare variables. It is advised to use let instead of var to declare a variable. If you are targeting older version of browser, you can use var.
在 JavaScript 中,变量是数据存储容器。你可以使用变量存储任何类型的数据。例如,字符串、数字、布尔值、对象等。
In JavaScript, variables are the data storage container. You can use the variables to store any type of data. For example, string, number, boolean, object, etc.
用 var 关键字声明的变量具有函数范围。而用 let 声明的变量具有块范围。
A variable declared with var keyword has function scope. Whereas a variable declared with let has block scope.
Syntax
按照下面的语法使用“var”关键字来定义变量。
Follow the syntax below to define the variable using the 'var' keyword.
var identifier;
var identifier = value;
在此,标识符可以是有效的变量名。在第 JavaScript - Variables 章中,我们已经讨论了定义有效标识符的规则。
Here, the identifier can be a valid variable name. In the JavaScript - Variables chapter, we have already discussed the rules to define valid identifiers.
在使用 JavaScript “var”关键字声明变量时,你可以给变量赋值,也可以不赋值。
You may assign or not value to the variable while declaring it using the JavaScript 'var' keyword.
Example
在下面的代码中,我们使用“var”关键字定义了 3 个变量。在 num1 变量中,我们存储了数字值。在 str1 变量中,我们存储了字符串值;在 bool 变量中,我们存储了布尔值。
In the below code, we have defined the 3 variables using the 'var' keyword. In the num1 variable, we have stored the numeric value. In the str1 variable, we have stored the string value; in the bool variable, we have stored the boolean value.
<html>
<body>
<div id = "output1"> </div>
<div id = "output2"> </div>
<div id = "output3"> </div>
<script>
var num1 = 30;
var str1 = "Hello World!";
var bool = true;
document.getElementById('output1').innerHTML = num1;
document.getElementById('output2').innerHTML = str1;
document.getElementById('output3').innerHTML = bool;
</script>
</body>
</html>
30
Hello World!
true
JavaScript Variable Scopes
使用 JavaScript “var”关键字定义的变量的作用域具有 function scope 或 global scope 。
The scope of the variable defined using the JavaScript 'var' keyword has a function scope or global scope.
JavaScript Function Scope
当你使用 var 关键字在函数内部定义变量时,可以在任何地方在函数内部访问它。即使你在函数内的特定块内使用 var 关键字定义变量,也可以在任何地方访问它。
When you define the variable inside the function using the var keyword, it can be accessible inside the function anywhere. Even if you define the variable using the var keyword inside the particular block inside the function, it can be accessible anywhere.
让我们通过下面的示例了解函数作用域。
Let’s understand the function scope with the example below.
Example
在下面的代码中,我们在函数内定义了变量“x”。我们还在函数内的块内定义了变量“y”。
In the below code, we have defined the variable 'x' inside the function. We have also defined the variable 'y' inside the block, which is inside the function.
之后,我们在函数内访问变量 x 和 y。
After that, we access the variables x and y inside the function.
<html>
<body>
<div id = "demo1"> </div>
<div id = "demo2"> </div>
<script>
function demo() {
var x = 10;
{
var y = 20;
// x and y both can be accessible here
}
document.getElementById('demo1').innerHTML = "X == " + x;
document.getElementById('demo2').innerHTML = "Y == " + y;
}
demo();
</script>
</body>
</html>
X == 10
Y == 20
如果你在函数内的块内使用 let 关键字定义变量,并且尝试在块外访问它,它将抛出错误。
If you define the variable using the let keyword inside the block, which is inside the function, and try to access it outside the block, it will throw an error.
JavaScript Global Scope
如果你在函数或特定块外部使用“var”关键字定义变量,它将成为全局变量。
It becomes the global variable if you define the variable using the 'var' keyword outside the function or a particular block.
之后,你可以在代码中的任何地方使用 window 对象访问该变量。
After that, you can access the variable anywhere inside the code using the window object.
Example
我们在下面的代码中定义了“num1”全局变量。
We have defined the 'num1' global variable in the code below.
之后,我们使用和不使用 window 对象在函数内访问“num1”变量。
After that, we access the 'num1' variable inside the function using and without using the window object.
<html>
<body>
<div id = "output"> </div>
<script>
const output = document.getElementById('output');
var num1 = 10;
function sum(num2) {
output.innerHTML += "num1 + num2 = " + (num1 + num2) + "<br>";
output.innerHTML += "window.num1 + num2 = " + (window.num1 + num2);
}
sum(20);
</script>
</body>
</html>
num1 + num2 = 30
window.num1 + num2 = 30
JavaScript Variable Hoisting
使用“var”关键字定义的变量会提升到其作用域的顶部。这意味着 JavaScript 会在变量的作用域顶部添加对变量的声明。
The variable defined using the 'var' keyword is hoisted at the top of its scope. It means JavaScript adds the declaration of the variable at the top of its scope.
因此,你可以在变量声明之前访问变量。
So you can access the variable before the declaration of the variable.
Example
在下面的代码中,我们初始化了变量“a”,并在其声明之前打印了它的值。
In the below code, we have initialized the variable 'a' and printed its value before its declaration.
代码运行不会出错,因为使用 var 关键字定义的变量会提升到其作用域的顶部。
The code runs without error, as the variable defined using the var keyword is hoisted at the top of its scope.
<html>
<body>
<div id = "output">Value of the variable a is: </div>
<script>
function checkHoisting() {
a = 98;
document.getElementById('output').innerHTML += a;
var a;
}
// You can't access the variable a here.
checkHoisting();
</script>
</body>
</html>
Value of the variable a is: 98
上面的 JavaScript 代码类似于下面的代码。
The above JavaScript code is similar to the below code.
var a;
a = 98;
document.getElementById('output').innerHTML += a;
Redeclaration of variable defined using the 'var' keyword
你可以使用“var”关键字重新声明变量,代码会毫无错误地运行。
You can redeclare the variables using the 'var' keyword, and the code will run without any error.
如果你用最新值初始化最后一个重复变量,它将会包含该值。但如果你不初始化最后一个重复变量,变量将包含其前一个值而不会丢失它。
If you have initialized the last duplicate variable with the latest value, it will contain that value. But if you don’t initialize the last duplicate variable, the variable will contain its previous value without losing it.
Example
在下面的代码中,我们定义了变量“a”两次,并用不同的值初始化它。你可以从输出中观察到变量“a”包含最后的值。
In the code below, we have defined the variable 'a' two times and initialized it with different values. You can observe in the output that variable 'a' contains the last value.
我们定义了变量“a”第三次,但没有初始化它。因此,它包含变量“a”的第二个值。
We have defined the variable 'a' a third time and haven’t initialized it. So, it contains the value of the 2nd 'a' variable.
<html>
<body>
<div id = "demo"> </div>
<script>
const output = document.getElementById('demo');
var a = 10;
var a = 20;
output.innerHTML += "The value of the a is: " + a + "<br>";
var a;
output.innerHTML += "The value of the a is: " + a;
</script>
</body>
</html>
The value of the a is: 20
The value of the a is: 20
如果你在不同的范围内定义重复变量,它可以根据你访问变量的位置来获取值。
If you define the duplicate variables in the different scopes, it can have value according to where you access the variable.
Example
在下面的代码中,我们在函数外部和内部定义了“num”变量。当你访问函数内部或外部时,它会输出不同的值。
In the code below, we have defined the 'num' variable outside and inside the function. When you access it inside or outside the function, it prints the different values.
<html>
<body>
<div id = "demo"> </div>
<script>
const output = document.getElementById('demo');
var num = 10;
function printNum() {
var num = 20;
output.innerHTML += "Num inside the function is: " + num + "<br>";
}
printNum();
output.innerHTML += "Num outside the function is: " + num + "<br>";
</script>
</body>
</html>
Num inside the function is: 20
Num outside the function is: 10
Declaring Many Variables in a Single Statement
如果你想使用 JavaScript “var”关键字声明多个变量,你可以在一条语句中声明所有变量。它使代码可读性更强。
If you want to declare multiple variables using the JavaScript 'var' keyword, you can declare all variables in a single statement. It makes code readable.
Example
在下面的代码中,我们在单条语句中声明了变量“a”和“b”,并在声明后用不同的值对其进行了初始化。
In the below code, we have declared the variables 'a' and 'b' in the single statement and initialized them with different values after declaring.
<html>
<body>
<div id = "output1"> </div>
<div id = "output2"> </div>
<script>
var a, b;
a = 70;
b = 80;
document.getElementById('output1').innerHTML = "The value of a is: " + a;
document.getElementById('output2').innerHTML = "The value of b is: " + b;
</script>
</body>
</html>
The value of a is: 70
The value of b is: 80
不过,你也可以在单条语句中声明多个变量时给变量赋值。
However, you can also assign the values to the variables while declaring the multiple variables in a single statement.
Using the var keyword with loops
当你使用 JavaScript “var”关键字定义 for 循环的迭代变量时,也可以在 for 循环外部访问它。
When you use the JavaScript 'var' keyword to define the iterator variable of for loop, you can also access it outside the for loop.
Example
在下面的代码中,我们定义了 for 循环内部的变量“p”。我们在循环内部和外部访问变量 p。
In the below code, we have defined the variable 'p' inside the for loop. We access the variable p inside and outside the loop.
<html>
<body>
<div id = "output"> </div>
<script>
const output = document.getElementById('output');
for (var p = 0; p < 5; p++) {
output.innerHTML += "The value of p is: " + p + "<br>";
}
output.innerHTML += "The value of p outside the loop is: " + p;
</script>
</body>
</html>
The value of p is: 0
The value of p is: 1
The value of p is: 2
The value of p is: 3
The value of p is: 4
The value of p outside the loop is: 5
Declaration with Destructuring
在 JavaScript 中,你可以在解构数组或对象时使用“var”关键字声明变量。
In JavaScript, you can declare the variables using the 'var' keyword while destructuring the array or objects.
Example
在下面的代码中,“arr”数组包含 3 个变量。
In the below code, the 'arr' array contains 3 variables.
之后,我们使用“var”关键字定义变量并解构数组。
After that, we define variables using the 'var' keyword and destructure the array.
<html>
<body>
<div id = "output"> </div>
<script>
const output = document.getElementById('output');
var arr = [4, 5, 6];
var [a, b, c] = arr;
output.innerHTML = "a = " + a + ", b = " + b + ", c = " + c;
</script>
</body>
</html>
a = 4, b = 5, c = 6
你还可以使用“var”关键字定义变量并存储对象或函数表达式。
You can also use the 'var' keyword to define the variables and store the objects or function expressions.