在本教程中,我们将了解JavaScript Variable的基本概念。本文仅关注JavaScript变量。 的JavaScript被称为网络语言,是最好的编程语言之一。
定义
的JavaScript变量用于将信息存储在容器中。它可以用于存储任何类型的值,包括字符串,数字,数组,布尔值等。 Every value that you store in 的JavaScript uses a name (known as 变种iable name) for storing and referencing purposes.
例如 :
变种 website = "Geeks Trick | 以棘手的方式编码";
// 'website' Is A Variable Name
To understand how 变种iable works, we need to understand three important terms:
不管使用哪种编程语言,如何创建和分配变量的概念都将帮助您深入理解高级概念。
声明类型
像许多其他编程语言一样,JavaScript具有变量。可以将变量视为命名容器。您可以将数据放入这些容器中,然后只需命名容器即可引用数据。
Before you use a 变种iable in a 的JavaScript program, you must declare it. Variables are declared with the 变种 关键字如下。
变种 website;
变种 description;
You can also declare multiple 变种iables with the same 变种 keyword as follows:
变种 website, description;
初始化JavaScript变量
声明变量后,变量初始化会自动发生。初始化时,内存由JavaScript引擎分配,您可以为其分配值。
// this is declaring and initializing with undefined
变种 example;
赋值
最后一步包括分配,并在设置值时完成。
So how to declare 变种iable type in 的JavaScript?
Declaring 变种iable is very easy. There are already available constructs you need to use to declare a 变种iable.
VAR
变种 is the most used way of declaring a 变种iable. The below code explains how to do it.
var webSite; // declaring and initializing a 变种iable.
webSite = "Geeks Trick | 以棘手的方式编码"; // Assigning a 变种iable.
另外,您可以使用以下代码在一行代码中进行声明,初始化和赋值。
var webSite = "Geeks Trick | 以棘手的方式编码";
注意: 在函数内部声明变量时,其范围与函数本身有关。如果在函数外部声明变量,则该变量具有全局作用域。我们将在本指南的后面部分介绍它。
从深处掩盖 这里
const Javascript变量
const可从ES6(ES2015)规范获得。
const 用于将值赋给变量一次,并且始终在块级工作。这意味着其范围已绑定到块级别。那么,const的用例是什么?
const 在使用迭代器或一次声明一个值时可以使用。但是,const不是声明不可变变量的解决方案。它以不同的方式工作。它可以确保引用是不可变的,但对值的引用却不相同。这意味着可以更改该值,但是不能使用const进行重新分配。
让我们来看一个例子:
function example() {
const x = "y"
if (true) {
const x // 变种iable not assigned, SyntaxError
const x = "b"
foo = "z" // 变种iable cannot be re-assigned, SyntaxError
console.log(x)
// b as const is available in this scope
}
console.log(x)
// y as const is available to the higher scope.
}
从深处掩盖 这里
让 Javascript变量
让 allows you to declare 变种iables that are limited in scope to the block, statement, or expression on which it is used. This is unlike the 变种 keyword, which defines a 变种iable globally, or locally to an entire function regardless of block scope.
范围规则
声明的变量 让 具有定义它们的块以及任何包含的子块作为其范围。通过这种方式, 让 工作非常像 变种。主要区别在于 变种 变种iable is the entire enclosing function:
function 变种Test() {
变种 x = 1;
if (true) {
变种 x = 2; // same 变种iable!
alert(x); // 2
}
alert(x); // 2
}
function 让Test() {
让 x = 1;
if (true) {
让 x = 2; // different 变种iable
console.log(x); // 2
}
console.log(x); // 1
}
从深处掩盖 这里
学到的概念
Things to learn from the different ways of declaring 变种iables are as follows:
- const is great for local 变种iable initialization, especially in iterators.
- 让 can be used in place to 变种 if you know what you are doing.
- 让 非常适合使用块级别控制。例如,您可以在循环时使用它。这样,您就不必担心以前使用的类似命名的变量。
获取更多帖子 的JavaScript