javascript - Question about why the value of i is equal to 5
欧阳克
欧阳克 2017-06-12 09:29:37
0
8
877
(function(){
    for(var i = 0; i < 5; i++) {}
    console.log(i) // i = 5
})()

First question: Which part of js knowledge does this belong to?
Second question: Explain in layman’s terms why i is equal to 5?
0o0

欧阳克
欧阳克

温故而知新,可以为师矣。 博客:www.ouyangke.com

reply all(8)
Ty80

Is this problem a closure? I don’t think it is a closure, and there is no nesting of functions. It is a problem of function local variables and anonymous functions.

Creating an anonymous function and executing it immediately does not involve closures. Just when the loop ends, the value of i becomes 5 and exits the loop, console.log(i)prints the current i, which is 5.

This is equivalent to:

var test = function() {
    for(var i = 0; i < 5; i++) {}
    console.log(i) // i = 5
}
test();
扔个三星炸死你

This is not a closure, it’s just a value printed after the for loop speed

刘奇

This is a problem caused by js not having block-level scope, only function scope. . . Ju can directly pull the closure. . . I accept it. . .

伊谢尔伦

There is no such thing as block-level scope in JavaScript, so the variables inside the for loop {} and if statement {} can be accessed from the outside.

Scope is divided into global scope and local scope

The global scope is built in by the system for you when you create a document.
Local scope is achieved by creating a function.

刘奇
  • This usually appears in the problem of examining closures

  • i + 1 looped 5 times, so i is 5

左手右手慢动作
  1. You should want to know about closures in js

  2. Because the for loop execution is completed when console.log is executed, i is naturally equal to 5

刘奇

Let’s take a look at closures combined with timers, or event binding

左手右手慢动作

Closures in js,

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!