This article brings you relevant knowledge about javascript, which mainly introduces the detailed explanation of var and let in JavaScript variables or loops. The article introduces the content in detail around the theme, which has certain For reference value, let’s take a look at it below. I hope it will be helpful to everyone.
[Related recommendations: javascript video tutorial, web front-end]
Use var in a for loop Problems caused by declaration initialization
// 一道经典面试题: var funcs = []; for (var i = 0; i < 3; i++) { funcs[i] = function() { console.log("My value: " + i) }; } for (var j = 0; j < 3; j++) { funcs[j](); } /* 输出结果: > My value: 3 > My value: 3 > My value: 3 */
The reason why this phenomenon occurs is:
- The scope of the var declaration is the function scope rather than the block level scope, so the var variable defined when initializing the for loop can still be accessed outside the loop body of the for loop.
- And when accessed after the loop ends, the var variable accessed is the value after the loop has completed.
Solution
Use closures
The solution in the ES5 era is to create a closure through IIFE, save the variables in the function body, and then execute the function The outer var variable will not be accessed.
var funcs = []; for (var i = 0; i < 3; i++) { // 1. 闭包 funcs[i] = (function (i) { return function () { console.log("My value: " + i); }; })(i); } for (var j = 0; j < 3; j++) { funcs[j](); }
Use let variable initialization
The let statement is a block-level scope, and the variables in the loop body will not be leaked outside the block statement.
Therefore, when accessing variable i after the loop ends, there is no interference from the outer scope variables, and what is accessed is naturally the variable value saved in the function body.
var funcs = []; // 2. let for (let i = 0; i < 3; i++) { funcs[i] = function() { console.log("My value: " + i); }; } for (var j = 0; j < 3; j++) { funcs[j](); }
It can also be seen from here that using var to initialize the for loop itself is counterintuitive.
The variable used to initialize the for loop should be a local variable of the for loop. This variable should have no meaning after the loop ends.
But if you use var to initialize, since the scope of the variable declared by var is the function scope, this initialization variable is in the same scope as the for loop and is not restricted by the for loop.
It should be a local variable of the for loop, but it is exposed in the scope of the same layer as the for loop, and the variable value has been changed by the number of loops, which will naturally affect the access of other codes to the variable after the loop ends. .
If you use let to initialize a for loop, you will not have this problem, because the scope declared by let is a block-level scope, and this initialization variable will become a local variable of the for loop as expected.
How does the for loop handle initialization variables declared with let and var?
First the conclusion:
- When initializing with var, the for loop will directly use the created var to initialize the variable;
- Initialize with let , the parentheses will form a scope of their own, and the for loop will pass the variable value within the parentheses to the loop body.
First let’s look at the first conclusion, the specification says this:
Yes It can be seen that the specification does not have any special treatment for var initialization variables, so it can be used directly. At this time this variable is an ordinary var variable and is in the same scope as the for loop.
Let’s use code to prove it:
var funcs = []; for (var i = 0; i < 3; i++) { // !!!重复声明了一个同名的var变量 var i = 5; console.log("My value: " + i); } /* 只会输出一次: > My value: 5 */
var can be declared repeatedly and the value will be overwritten, so declare another var i in the loop body = 5
, the loop variable is destroyed, and the for loop will be jumped out directly.
var funcs = []; for (var i = 0; i < 3; i++) { // 用let声明了一个和循环变量同名的变量 let i = 5; console.log("My value: " + i); } /* 一共输出了3次: > My value: 5 > My value: 5 > My value: 5 */
Initialize the var variable in the function scope, and the let variable in the loop body is in the block scope. The let variable in the loop body has priority to access the let variable in the block scope, so the i value in the loop body will be overwritten.
And because the var variable is actually in the outer scope of the let variable, the let variable is not declared repeatedly and no error is reported; the var variable will also complete its mission as a loop variable as scheduled.
Let’s look at the second conclusion, also looking at the specification first:
It is obvious that using let to initialize will have one more call ## than using var. #perIterationLets stuff.
perIterationLetsWhat is it?
perIterationLets comes from
boundNames in
LexicalDeclaration (lexical declaration) .
LexicalDeclaration (lexical declaration) is actually the let statement we use to initialize.
perIterationLets and then passed to the loop body.
perIterationLetsWhat is
used for?
ForBodyEvaluation as a parameter as
perIterationLets, which is the loop body .
perIterationLets only does one thing, that is, as a parameter of
CreatePerIterationEnvironment:
从字面上理解,CreatePerIterationEnvironment
意思就是每次循环都要创建的环境。
要注意,这个环境不是{...}
里的那些执行语句所处的环境。 {...}
里的执行语句是statement
,在规范里可以看到,stmt
有自己的事情要做。
这个环境是属于圆括号的作用域,也就是我们定义的let初始化变量所在的作用域。
再看看每次循环都要创建的环境被用来干嘛了:
逐步分析一下方法:CreatePerIterationEnvironment
这个
- 首先,把当前执行上下文的词法环境保存下来,作为
lastIterationEnv(上一次循环时的环境)
; - 创建一个和
lastIterationEnv
同级的新作用域,作为thisIterationEnv(本次循环的环境)
; - 遍历我们定义的let初始化变量,也就是
perIterationLets
,在thisIterationEnv(本次循环的环境)
里创建一个同名的可变绑定,找到它们在lastIterationEnv(上一次循环时的环境)
里的终值,作为这个同名绑定的初始值; - 最后,将
thisIterationEnv(本次循环的环境)
交还给执行上下文。
简而言之就是,for循环会在迭代之前创建一个和初始化变量同名的变量,并使用之前迭代的终值将这个变量初始化以后,再交还给执行上下文。
用伪代码理解一下这个过程就是:
到这里又有一个问题,既然把圆括号内的变量向循环体里传递了,那如果在循环体里又重复声明了一个同名变量,算不算重复声明,会不会报错?
答案是不会。
因为CreatePerIterationEnvironment
在执行时,在新环境里创建的是一个可变的绑定,因此如果在循环体内重复声明一个名字为i
的变量,只是会影响循环体内执行语句对i
值的访问。
var funcs = []; for (let i = 0; i < 3; i++) { // !!!用let声明了一个和循环变量同名的变量 let i = 5; console.log("My value: " + i); } /* 一共输出了3次: > My value: 5 > My value: 5 > My value: 5 */
总结
在for循环中使用var声明来初始化的话,循环变量会暴露在和for循环同一作用域下,导致循环结束后还能访问到循环变量,且访问到的变量值是经过循环迭代后的值。
解决这个问题的方法如下:
- 使用闭包将循环变量的值作为局部变量保存起来;
- 使用ES6的let声明,将循环变量的作用域限制在for循环内部,初始化变量始终是for循环的局部变量,不能在外界被访问到。
for循环是怎么处理用let和var声明的初始化变量的?
- 用var初始化时,for循环会直接使用创建的var初始化变量;
- 用let初始化时,圆括号会自成一个作用域,for循环会将圆括号内的变量值往循环体内传递。
【相关推荐:javascript视频教程、web前端】
The above is the detailed content of Briefly understand var and let in JavaScript variables or loops. For more information, please follow other related articles on the PHP Chinese website!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6
Visual web development tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment