JavaScript 教程 - 变量
我们将在本教程中学习 JavaScript 变量。
JavaScript 变量定义
程序中使用了变量来存储信息。它可以是访问者的年龄,也可以是用户名。该变量存储信息,以后可以再次使用。
你可以将 JavaScript 变量命名为几乎所需的任何名称,但是有一些规则:
变量标识符规则
- 变量可以由字母、数字和下划线组成,但必须以小写字母、大写字母或下划线开头,不能以数字开头。
- 你不得使用任何 JavaScript 关键字。
- 变量名称区分大小写。
- 变量名称不能包含空格。
声明一个变量
语法
var <variable - name>;
// or
var <variable - name> = <value>;
JavaScript 变量声明示例
var x = 1;
你需要先声明一个变量,然后才能使用它。你可以使用关键字 var
,然后使用变量名,如上例所示的 x
。你可以将变量的值与声明一起初始化,也可以稍后为其分配值。
JavaScript 具有动态变量数据类型,你可以毫无问题地为变量分配不同的数据类型。
这一点不同于其他编程语言中的在声明变量时必须指定变量的类型,并且后继不能更改类型。
JavaScript 多变量声明
可以在一行中用逗号 ,
分隔声明多个变量。
var one, two, three = 1, 2, 3;
JavaScript 中不带 var
的变量声明
我们可以在 JavaScript 中声明一个不带 var
的变量,但是需要直接分配值给变量。
one = 1;
two = 2;
three, four = 3, 4;
ES6 中的 let
和 const
变量
var
关键字声明在函数范围内的变量,但是在 ES6 引入的 let
和 const
关键字可变范围扩大到块 {}
级别。
用 const
关键字声明的变量在声明后不能重新分配值,但是用 let
声明的可以。
> let A = '1' > A = '2'
'2' > const B = 1;
> B = 2
VM944: 1 Uncaught TypeError: Assignment to constant variable.at<anonymous>: 1: 3
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。