javascript和var之间的区别?

You can define your variables in JavaScript using two keywords - the let keyword and the var keyword. The var keyword is the oldest way of defining and declaring variables in JavaScript whereas the let is fairly new and was introduced by ES15.

您可以使用两个关键字( let关键字和var关键字) 在JavaScript中定义变量 。 var关键字是在JavaScript中定义和声明变量的最古老的方法,而let是相当新的,是ES15引入的。

In this article, we'll look at the differences between the two so you know when to use which for your variables.

在本文中,我们将研究两者之间的区别,以便您知道何时将哪个变量用于变量。

Open the chrome dev console to try out the examples by right-clicking on the browser → selecting inspect → selecting console or simply type f12.

通过右键单击浏览器→选择检查→选择控制台,打开chrome dev控制台以尝试示例,或者直接键入f12。

Example 1:

范例1:

var size=32;
console.log(size);

Output

输出量

32

Example 2:

范例2:

var size=63;
console.log(size);

Output

输出量

63

We declared a variable size with a value 32. Then we redeclared it with another value, 63. Everything looks fine till now.

我们声明了一个可变大小,值为32 。 然后,我们用另一个值63对其进行了重新声明。 到目前为止一切都很好。

let length=14;
console.log(length);

Output

输出量

14

let length=14;
let length=20; //will produce error
console.log(length);

Output

输出量

Uncaught SyntaxError: Identifier 'length' has already been declared
at <anonymous>:1:1

let length=14;
length=20; //no produce error
console.log(length);

Output

输出量

20

Now we create a length variable with a value 14 but this time using the let keyword. When we redeclare the same variable with another value we get a SyntaxError saying it has already been declared. The first point of difference between let and var is that using var we can redeclare those variables but with let, we can only redefine them, not redeclare them. When we reassign the value 20 to the variable length, we get no error on the console and our length variable happily takes a new value.

现在我们创建一个长度变量,值为14,但是这次使用let关键字 。 当我们用另一个值重新声明相同的变量时,我们得到一个SyntaxError,它已经被声明。 let和var之间的第一点区别是,使用var可以重新声明这些变量,但是使用let ,我们只能重新定义它们,而不能重新声明它们。 当我们将值20重新分配给变量length时 ,在控制台上没有错误,并且我们的length变量愉快地采用了一个新值。

var ironMan = 'red';
var captainAmerica = 'blue';
if (ironMan === 'red') {
var ironMan = 'silver';
let captainAmerica = 'golden';
console.log(ironMan);
console.log(captainAmerica);
}

Output

输出量

silver
Golden

var ironMan = 'red';
var captainAmerica = 'blue';
if (ironMan === 'red') {
var ironMan = 'silver';
let captainAmerica = 'golden';
console.log(ironMan);
console.log(captainAmerica);
}

Output

输出量

silver
Blue

The next difference between the two is the scope. You can observe from the above code that captainAmerica is declared again inside using the let keyword with a value 'golden' and inside that if block it persists that value, however, outside that if block when we log it's value to the console we get the older value 'blue' which was defined outside the if block. Thus variables declared using the let keyword have block scope. On the other hand, we changed the value of ironMan inside the if block and it continues to hold that value even after the if block is over. We can say that var takes the scope of it's enclosing execution context which can be a function or even the global scope as in this case.

两者之间的下一个区别是范围。 您可以从上面的代码中观察到,在captainAmerica内部再次使用let关键字声明了“黄金”值,并且在if块内部将其持久保留该值,但是在if块之外,当我们将其值记录到控制台时,我们得到了在if块外定义的旧值“ blue” 。 因此,使用let关键字声明的变量具有块范围。 另一方面,我们更改了if块内的ironMan的值, 即使 if块结束,它仍继续保持该值。 我们可以说var接受其封闭执行上下文的范围,在这种情况下,它可以是函数甚至是全局范围。

Heads up: The reason let was introduced was to avoid using global variables and namespaces everywhere. It's a bad, no wait, terrible programming habit. Avoid using global variables where their global scope renders absurd. Use let wherever possible.

注意:引入let的原因是为了避免在各处使用全局变量和名称空间。 这是一种不好的,迫不及待的可怕的编程习惯。 避免在全局变量变得荒谬的地方使用全局变量。 尽可能使用let

Finally, the last difference I want to talk about is Hoisting. Consider the following piece of code,

最后,我要谈的最后一个区别是吊装 。 考虑下面的代码,

x = 5;
console.log(x);
var x;

Output

输出量

5

If you've worked with languages like C/C++ you might find it strange. In such languages, you can expect an error saying something like x is not defined because compiler reads from top to bottom. So is JS also executed from top to bottom? Well, if it were, you wouldn't be able to do this. Then how come we can use a variable and declare it later? The answer is hoisting. Hoisting means moving all declarations to the top. This means that while executing the code, all variable declarations are on the top so till the time you come to x=5 line you already know that x has been declared a variable somewhere in the program.

如果您使用过C / C ++之类的语言,则可能会觉得很奇怪。 在这样的语言中,您可能会遇到一个错误,即未定义类似x的内容,因为编译器从上到下读取。 JS也是从头到尾执行吗? 好吧,如果是这样,您将无法做到这一点。 那么我们如何使用变量并在以后声明它呢? 答案正在提升。 吊装意味着将所有声明移到顶部。 这意味着在执行代码时,所有变量声明都位于顶部,因此直到您到达x = 5行时,您已经知道x已在程序中的某个位置声明为变量。

y = 3;
function setRandom(y) {
console.log('Before declaring y: ', y);
}
setRandom();
var y;
console.log('After declaring y: ', y);

Output

输出量

Before declaring y:  undefined
After declaring y:  3

Let's try to hoist a variable using let,

让我们尝试使用let提升变量,

x = 5;
console.log(x);
let x;

Output

输出量

VM2466:1 Uncaught ReferenceError: Cannot access 'x' before initialization
at <anonymous>:1:2

We get an error saying we can't access it before it is even initialized. So are variables declared with the let keyword not hoisted? They are, but they're hoisted in a temporal dead zone. A zone where you can use variables that have not been defined yet.

我们收到一条错误消息,说我们甚至无法在初始化之前访问它。 那么,没有悬挂用let关键字声明的变量吗? 它们是,但是它们被吊在一个临时的死区中。 您可以在其中使用尚未定义的变量的区域。

Note: if you are using strict mode in your JavaScript then you're more likely to run into getting undefined values for such types of code because strict mode does not allow any hoisting to take place.

注意:如果您在JavaScript中使用严格模式,那么您很可能会遇到此类代码的未定义值,因为严格模式不允许任何提升。

So is hoisting in TDZ useless? Well not really, consider the following example using an asynchronous function.

那么在TDZ中吊起是没有用的吗? 并非如此,请考虑以下使用异步函数的示例。

for (var i = 0; i < 3; i++) {
setTimeout(function() {
console.log(i);
}, 1000)
}

Output

输出量

3

Out setTimeout is an asynchronous function and after 1 sec it prints the value of i which was incremented 4 times while that asynchronous function was running. However if we use let instead of var,

setTimeout输出是一个异步函数,在1秒钟后它将打印i的值,该值在该异步函数运行时增加了4倍。 但是,如果我们使用let而不是var

for (let i = 0; i < 3; i++) {
setTimeout(function() {
console.log(i);
}, 1000)
}

Output

输出量

0
1
2

Now we get all the values that i took during that loop traversal. This is because of the TDZ or the temporal dead zone where let is hoisted. Thus using async can help you retain your values through TDZ hoisting if you use let instead of var. Remember to clean your code by replacing all var with let and make it a good practice to use block scopes instead of global scopes!

现在,我们所有的值, 我该循环遍历期间举行。 这是因为TDZ或悬挂了let 的时间盲区 。 因此,如果使用let而不是var,则使用async可以帮助您通过TDZ提升保留值。 请记住通过用let替换所有var来清理代码,并使其成为使用块范围而不是全局范围的好习惯!

翻译自: https://www.includehelp.com/code-snippets/var-vs-let-in-javascript.aspx

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/378273.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

小米手环6NFC安装太空人表盘

以前看我室友峰哥、班长都有手环&#xff0c;一直想买个手环&#xff0c;不舍得&#xff0c;然后今年除夕的时候降价&#xff0c;一狠心&#xff0c;入手了&#xff0c;配上除夕的打年兽活动还有看春晚京东敲鼓领的红包和这几年攒下来的京东豆豆&#xff0c;原价279的小米手环6…

计算机二级c语言题库缩印,计算机二级C语言上机题库(可缩印做考试小抄资料)...

小抄,答案,形成性考核册,形成性考核册答案,参考答案,小抄资料,考试资料,考试笔记第一套1.程序填空程序通过定义学生结构体数组&#xff0c;存储了若干个学生的学号、姓名和三门课的成绩。函数fun 的功能是将存放学生数据的结构体数组&#xff0c;按照姓名的字典序(从小到大排序…

为什么两层3*3卷积核效果比1层5*5卷积核效果要好?

目录1、感受野2、2层3 * 3卷积与1层5 * 5卷积3、2层3 * 3卷积与1层5 * 5卷积的计算量比较4、2层3 * 3卷积与1层5 * 5卷积的非线性比较5、2层3 * 3卷积与1层5 * 5卷积的参数量比较1、感受野 感受野&#xff1a;卷积神经网络各输出特征像素点&#xff0c;在原始图片映射区域大小。…

算法正确性和复杂度分析

算法正确性——循环不变式 算法复杂度的计算 方法一 代换法 —局部代换 这里直接对n变量进行代换 —替换成对数或者指数的情形 n 2^m —整体代换 这里直接对递推项进行代换 —替换成内部递推下标的形式 T(2^n) S(n) 方法二 递归树法 —用实例说明 —分析每一层的内容 —除了…

第十五章 Python和Web

第十五章 Python和Web 本章讨论Python Web编程的一些方面。 三个重要的主题&#xff1a;屏幕抓取、CGI和mod_python。 屏幕抓取 屏幕抓取是通过程序下载网页并从中提取信息的过程。 下载数据并对其进行分析。 从Python Job Board&#xff08;http://python.org/jobs&#x…

array_chunk_PHP array_chunk()函数与示例

array_chunkPHP array_chunk()函数 (PHP array_chunk() Function) array_chunk() function is an array function, it is used to split a given array in number of array (chunks of arrays). array_chunk()函数是一个数组函数&#xff0c;用于将给定数组拆分为多个数组(数组…

raise

raise - Change a windows position in the stacking order button .b -text "Hi there!"pack [frame .f -background blue]pack [label .f.l1 -text "This is above"]pack .b -in .fpack [label .f.l2 -text "This is below"]raise .b转载于:ht…

c语言输出最大素数,for语句计算输出10000以内最大素数怎么搞最简单??各位大神们...

该楼层疑似违规已被系统折叠 隐藏此楼查看此楼#include #include int* pt NULL; // primes_tableint pt_size 0; // primes_table 数量大小int init_primes_table(void){FILE* pFile;pFile fopen("primes_table.bin", "rb");if (pFile NULL) {fputs(&q…

【数据结构基础笔记】【图】

代码参考《妙趣横生的算法.C语言实现》 文章目录前言1、图的概念2、图的存储形式1、邻接矩阵&#xff1a;2、邻接表3、代码定义邻接表3、图的创建4、深度优先搜索DFS5、广度优先搜索BFS6、实例分析前言 本章总结&#xff1a;图的概念、图的存储形式、邻接表定义、图的创建、图…

第十六章 测试基础

第十六章 测试基础 在编译型语言中&#xff0c;需要不断重复编辑、编译、运行的循环。 在Python中&#xff0c;不存在编译阶段&#xff0c;只有编辑和运行阶段。测试就是运行程序。 先测试再编码 极限编程先锋引入了“测试一点点&#xff0c;再编写一点点代码”的理念。 换而…

如何蹭网

引言蹭网&#xff0c;在普通人的眼里&#xff0c;是一种很高深的技术活&#xff0c;总觉得肯定很难&#xff0c;肯定很难搞。还没开始学&#xff0c;就已经败给了自己的心里&#xff0c;其实&#xff0c;蹭网太过于简单。我可以毫不夸张的说&#xff0c;只要你会windows的基本操…

android对象缓存,Android简单实现 缓存数据

前言1、每一种要缓存的数据都是有对应的versionCode&#xff0c;通过versionCode请求网络获取是否需要更新2、提前将要缓存的数据放入assets文件夹中&#xff0c;打包上线。缓存设计代码实现/*** Created by huangbo on 2017/6/19.** 主要是缓存的工具类** 缓存设计&#xff1a…

通信原理.绪论

今天刚上通信原理的第一节课&#xff0c;没有涉及过多的讲解&#xff0c;只是讲了下大概的知识框架。现记录如下&#xff1a; 目录1、基本概念消息、信息与信号2、通信系统模型1、信息源2、发送设备3、信道4、接收设备5、信宿6、模拟通信系统模型7、数字通信系统模型8、信源编…

Android版本演进中的兼容性问题

原文&#xff1a;http://android.eoe.cn/topic/summary Android 3.0 的主要变化包括: 不再使用硬件按键进行导航 (返回、菜单、搜索和主屏幕)&#xff0c;而是采用虚拟按键 (返回&#xff0c;主屏幕和最近的应用)。在操作栏固定菜单。 Android 4.0 则把这些变化带到了手机平台。…

css rgba透明_rgba()函数以及CSS中的示例

css rgba透明Introduction: 介绍&#xff1a; Functions are used regularly while we are developing a web page or website. Therefore, to be a good developer you need to master as many functions as you can. This way your coding knowledge will increase as well …

第十七章 扩展Python

第十七章 Python什么都能做&#xff0c;真的是这样。这门语言功能强大&#xff0c;但有时候速度有点慢。 鱼和熊掌兼得 本章讨论确实需要进一步提升速度的情形。在这种情况下&#xff0c;最佳的解决方案可能不是完全转向C语言&#xff08;或其他中低级语言&#xff09;&…

android studio资源二进制,无法自动检测ADB二进制文件 – Android Studio

我尝试在Android Studio上测试我的应用程序,但我遇到了困难"waiting for AVD to come online..."我读过Android设备监视器重置adb会做到这一点,它确实……对于1次测试,当我第二天重新启动电脑时,我不仅仅是&#xff1a;"waiting for AVD to come online..."…

犀牛脚本:仿迅雷的增强批量下载

迅雷的批量下载满好用。但是有两点我不太中意。在这个脚本里会有所增强 1、不能设置保存的文件名。2、不能单独设置这批下载的线程限制。 使用方法 // 下载从编号001到编号020的图片&#xff0c;保存名为猫咪写真*.jpg 使用6个线程 jdlp http://bizhi.zhuoku.com/bizhi/200804/…

为什么使用1 * 1 的卷积核

为什么使用 1* 1卷积核&#xff1f; 作用&#xff1a; 1、实现跨通道的交互和信息整合 2、 进行卷积核通道数的降维和升维 3、 在保持feature map尺度不变的&#xff08;即不损失分辨率&#xff09;的前提下大幅增加非线性特性 跨通道的交互和信息整合 使用1 * 1卷积核&a…

KingPaper初探ThinkPHP3.1.2之扩展函数库和类库的使用(四)

在我们做项目的时候TP的系统函数或系统类库满足不了我们的需要 所以有些东西需要我们自己去定义&#xff0c;在TP中我们怎么使用自己的函数库和类库呢&#xff1f;在TP系统中提供了三个系统函数库 common.php是全局必须加载的基础函数库&#xff0c;在任何时候都可以直接调用&a…