How to implement the following code using es6 let,
for(var i = 0; i < 3;i++) { (function(j){ $.ajax({ url: 'xxx', success: function(){ console.log(j); } })(i); }) }
for(let i = 0; i < 3;i++) { $.ajax({ url: 'xxx', success: function(){ console.log(i); }; }); }
What the questioner wants to ask is, how to solve i in ES6? Is it not a problem of the current i`?
i
ES6
i`?
ES5 it is solved using closures, in ES6 you can use let
it is solved using closures, in
you can use
for(let i = 0; i < 3;i++) { $.ajax({ url: 'xxx', success: function(){ console.log(i); } }); }
This is the same with ES6, closures are still closures.
Replace var with let
var
let
for(let i = 0; i < 3;i++) { $.ajax({ url: 'xxx', success: function(){ console.log(j); } }) }
The test is as follows (use setTimeout to simulate asynchronous requests):
for(var i = 0; i < 3;i++) { setTimeout(function(){ console.log(i) }, 123) }
Print 3 3
ES5 is solved with closure
for(var i = 0; i < 3;i++) { (function(i) { setTimeout(function(){ console.log(i) }, 123) })(i) }
es6 is easy with let
for(let i = 0; i < 3;i++) { setTimeout(function(){ console.log(i) }, 123) }
let allows you to declare a variable, statement or expression whose scope is restricted to the block level
I also found the answer, ES6 can directly remove closures
The result is the same as using closure, thank you everyone
There is absolutely no need in ES6, just let it be donehttp://www.softwhy.com/articl...
What the questioner wants to ask is, how to solve
Ini
inES6
? Is it not a problem of the currenti`?
ES5
it is solved using closures, in
ES6you can use
letThis is the same with ES6, closures are still closures.
Replace
var
withlet
The test is as follows (use setTimeout to simulate asynchronous requests):
ES5 is solved with closure
es6 is easy with let
I also found the answer, ES6 can directly remove closures
The result is the same as using closure, thank you everyone
There is absolutely no need in ES6, just let it be done
http://www.softwhy.com/articl...