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);
})
}
给我你的怀抱2017-06-30 10:01:41
for(let i = 0; i < 3;i++) {
$.ajax({
url: 'xxx',
success: function(){
console.log(i);
};
});
}
我想大声告诉你2017-06-30 10:01:41
What the questioner wants to ask is, how to solve i
in ES6
? Is it not a problem of the current i`?
ES5 it is solved using closures, in
ES6 you can use
let
for(let i = 0; i < 3;i++) {
$.ajax({
url: 'xxx',
success: function(){
console.log(i);
}
});
}
世界只因有你2017-06-30 10:01:41
Replace var
with 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
阿神2017-06-30 10:01:41
I also found the answer, ES6 can directly remove closures
for(let i = 0; i < 3;i++) {
$.ajax({
url: 'xxx',
success: function(){
console.log(i);
}
});
}
The result is the same as using closure, thank you everyone
PHP中文网2017-06-30 10:01:41
There is absolutely no need in ES6, just let it be done
http://www.softwhy.com/articl...