Javascript 简明教程

JavaScript - Variables

JavaScript Variables

JavaScript 变量被用来存储随后可更改的数据。这些变量可以被认为是有名称的容器。你可以将数据放入这些容器中,然后简单地通过命名该容器来引用数据。

JavaScript variables are used to store data that can be changed later on. These variables can be thought of as named containers. You can place data into these containers and then refer to the data simply by naming the container.

在 JavaScript 程序中使用变量之前,你必须声明它。在 JavaScript 中,你可以用 4 种方式声明变量 −

Before you use a variable in a JavaScript program, you must declare it. In JavaScript, you can declare the variables in 4 ways −

  1. Without using any keywords.

  2. Using the 'var' keyword.

  3. Using the 'let' keyword.

  4. Using the 'const' keyword.

letconst 关键词在 2015 年(ES6)引入 JavaScript 中。在 ES6 之前,只使用 var 关键词在 JavaScript 中声明变量。在本节中,我们将介绍“var”关键词。我们将在后续章节中介绍“let”和“const”关键词。

The let and const keywords were introduced to JavaScript in 2015 (ES6). Prior to ES6, only var keyword was used to declare the variable in JavaScript. In this section, we will discuss 'var' keyword. We will cover the 'let' and 'const' keywords in subsequent chapters.

Variable Declaration in JavaScript

无需使用任何关键字,您可以按照以下语法声明变量。

You can follow the syntax below to declare the variables without using any keywords.

<script>
   Money = 10;
   Name = "tutorialspoint";
</script>

此外,您可以使用 var 关键字声明变量,如下所示。

Furthermore, you can use the var keyword to declare the variables as shown below.

<script>
   var money;
   var name;
</script>

你也可以使用相同的 var 关键字声明多个变量,如下所示:

You can also declare multiple variables with the same var keyword as follows −

<script>
   var money, name;
</script>

Variable Initialization using the Assignment Operator

将值存储在变量中称为 variable initialization 。可以在创建变量时初始化变量,也可以在需要变量的稍后时间点进行初始化。

Storing a value in a variable is called variable initialization. You can do variable initialization at the time of variable creation or at a later point in time when you need that variable.

例如,你可能会创建一个名为 money 的变量,稍后为其分配 2000.50 的值。对于另一个变量,你可以在初始化时分配值,如下所示:

For instance, you might create a variable named money and assign the value 2000.50 to it later. For another variable, you can assign a value at the time of initialization as follows.

<script>
   var name = "Ali";
   var money;
   money = 2000.50;
</script>

Note − 只在文档中任何变量名的生命周期中使用 var 关键字进行声明或初始化。你不应重新声明同一个变量两次。

Note − Use the var keyword only for declaration or initialization, once for the life of any variable name in a document. You should not re-declare same variable twice.

JavaScript 是 untyped language 。这意味着 JavaScript 变量可以保存任何数据类型的值。与许多其他语言不同,在变量声明时不需要告知 JavaScript 变量将保存何种类型的值。变量的值类型可在程序执行期间发生变化,JavaScript 会自动处理。

JavaScript is untyped language. This means that a JavaScript variable can hold a value of any data type. Unlike many other languages, you don’t have to tell JavaScript during variable declaration what type of value the variable will hold. The value type of a variable can change during the execution of a program and JavaScript takes care of it automatically.

JavaScript Data Types

在 JavaScript 中,变量可以保存动态数据类型的值。例如,可以在 JavaScript 变量中存储数字、字符串、布尔值、对象等等数据类型值。

In JavaScript, the variable can hold the value of the dynamic data type. For example, you can store the value of number, string, boolean, object, etc. data type values in JavaScript variables.

<script>
   var num = 765; // Number
   var str = "Welcome"; // String
   var bool = false; // Boolean
</script>

您将在 JavaScript Data Types 中详细了解数据类型。

You will learn data types in detail in JavaScript Data Types chapter.

JavaScript Variable Names (Identifiers)

在 JavaScript 中,使用唯一字符序列对称为标识符的变量进行命名。

In JavaScript, a unique character sequence is used to name the variables called identifiers.

以下是一些有关在 JavaScript 中对标识符进行命名的规则:

Here are some rules for the naming of the identifiers in JavaScript −

  1. Valid characters − In JavaScript, a variable name can contain digits, alphabetical characters, and special characters like underscore (_) and dollar sign ($). JavaScript variable names should not start with a numeral (0-9). They must begin with a letter or an underscore character. For example, 123test is an invalid variable name but _123test is a valid one..

.

  1. Case sensitivity − Variable names are case sensitive. It means Name and name are different identifiers.

  2. Unicode support − The identifiers can also contain the Unicode. So, developers may define variables in any language.

  3. Reserve keywords − You should not use any of the JavaScript reserved keywords as a variable name. For example, break or boolean variable names are not valid. Here, we have given a full list of the JavaScript revered keywords.

JavaScript Dollar Sign ($) and Under Score (_)

您可以使用 $ 和 _ 在 JavaScript 中定义变量,因为 JavaScript 引擎将其视为有效字符。

You can use the $ and _ to define the variables in JavaScript, as the JavaScript engine considers it a valid character.

Example (Demonstrating the identifiers)

在此示例中,我们使用 var 关键字定义了变量。第一个变量名以下划线开头,第二个变量名以美元符号开头。程序员可以取消对第三个变量声明的注释,以检查当我们从数字开始任何标识符时 JavaScript 生成的错误。

In this example, we have defined the variables using the var keyword. The first variable name starts with the underscore, and the second variable name starts with the dollar sign. Programmers can uncomment the third variable declaration to check the error generated by JavaScript when we start any identifier with the digit.

<html>
<head>
    <title> Variables in JavaScript </title>
</head>
<body>
   <script>
        var _abc = "Hi!";
        var $abc = "Hello!";
        //  var 9abc = "Bye!";  // This is invalid
        document.write("_abc " + _abc + "<br>");
        document.write("$abc = " + $abc + "<br>");
    </script>
</body>
</html>

它生成以下结果:

It produces the following result −

_abc Hi!
$abc = Hello!

Undefined Variable Value in JavaScript

在声明后不初始化变量时,它包含 undefined 值。不过,您还可以将 undefined 值分配给变量。

When you don’t initialize the variable after declaring, it contains the undefined value. However, you can also assign the undefined value to the variable.

我们来看一下下面的示例。

Let’s look at the example below.

Example

<html>
<body>
   <script>
      var num;
      document.write("The value of num is: " + num + "<br/>");
   </script>
</body>
</html>

这会产生以下结果:

This produces the following result −

The value of num is: undefined

JavaScript Variable Scope

变量的范围是程序中定义它的区域。JavaScript 变量只有两个范围。

The scope of a variable is the region of your program in which it is defined. JavaScript variables have only two scopes.

  1. Global Variables − A global variable has global scope which means it can be defined anywhere in your JavaScript code.

  2. Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.

在函数体中,局部变量优于具有相同名称的全局变量。如果使用全局变量的相同名称声明局部变量或函数参数,则可以有效隐藏全局变量。了解以下示例。

Within the body of a function, a local variable takes precedence over a global variable with the same name. If you declare a local variable or function parameter with the same name as a global variable, you effectively hide the global variable. Take a look into the following example.

Example

在下面的示例中,我们已定义了名为 myVar 的变量(在函数外部),并将其初始化为 'global' 值。此外,我们已定义具有相同标识符的变量(在 checkscope() 函数内部),并将其初始化为 'local' 值。

In the example below, we have defined the variable named myVar outside the function and initialized it with the 'global' value. Also, we have defined the variable with the same identifier inside the checkscope() function and initialized it with the 'local' value.

我们在函数内部打印 myVar 变量值。因此,局部变量优先于全局变量,并在输出中打印 'local'。

We print the myVar variable’s value inside the function. So, the local variable takes preference over the global variable and prints the 'local' in the output.

<html>
<head>
   <title> JavaScript Variable Scope Example</title>
</head>
<body onload = checkscope();>
   <script>
	  var myVar = "global";      // Declare a global variable
	  function checkscope( ) {
		 var myVar = "local";    // Declare a local variable
		 document.write(myVar);
	  }
   </script>
</body>
</html>

这会产生以下结果:

This produces the following result −

local

Example

在下面的示例中,我们已定义变量,但未使用 var 关键字。 name 变量包含 string 类型的值,而 number 变量包含 float 数据类型的

In the example below, we have defined the variables without using the var keyword. The name variable contains the value of the string type, and the number variable contains the value of the float data type.

如果我们不使用任何关键字来定义变量,JavaScript 将其视为全局变量,且可以在代码内的任何位置使用它们。

When we define the variables without using any keyword, JavaScript considers them global variables and can use them anywhere inside the code.

<html>
<head>
   <title> Variables without var keyword </title>
</head>
<body>
   <script>
      name = "tutorialspoint"; // String type variable
      number = 10.25; // Number type variable
      document.write("name = " + name + ", number = " + number + "<br>");
   </script>
</body>
</html>

这会产生以下结果:

This produces the following result −

name = tutorialspoint, number = 10.25

此外,如果我们使用具有值的 var 关键字来声明变量,并重新声明相同的标识符而未进行初始化,则该标识符不会丢失先前的值。让我们通过以下示例来理解。

Also, the identifier doesn’t lose the previous value if we declare the variable using the var keyword with the value and re-declare the same identifier without initialization. Let’s understand it via the example below.

Example

在下面的示例中,我们声明了 age 变量并用 10 对其进行了初始化。我们再次声明 age 变量,但未对其进行初始化。即使如此,它仍会输出 10,因为它不会丢失先前的初始化值。但是,如果我们更新 age 变量的值,它会成功更新该值。

In the example below, we have declared the age variable and initialized it with 10. Again, we have declared the age variable but haven’t initialized it. Still, it prints 10 in the output because it doesn’t lose the previous initialization’s value. However, if we update the value of the age variable, it successfully updates it.

<html>
<head>
   <title> Variables with var keyword </title>
</head>
<body>
   <script>
      var age = 10;
      var age;
      document.write("age = " + age + "<br>");
   </script>
</body>
</html>

这会产生以下结果:

This produces the following result −

age = 10