This time I will bring you a detailed explanation of the use of var and let in the for loop in jQuery. What are the precautions for using var and let in the for loop in jQuery? , the following is a practical case, let’s take a look.
Today I found a problem when writing the jQuery request interface: When sending a request using AJAX, another AJAX request was nested. It was found that the success of the inner request was not correct for the first success. The loop variable i in cannot be obtained. The specific code is as follows:$.ajax({ type: "get", url: "//////////////////////////", success: function (result) { rs = JSON.parse(result).data; for (var i = 0; i < rs.length; i++) { //用var定义有问题 var pos_ = "" $.ajax({ type: 'GET', async: false, dataType: 'jsonp', contentType: 'application/json; charset=utf-8', url: "///////////////////////////////////", success: function (result) { console.log(rs[i]) //报错 } }) } } })
callback function after the second ajax request, rs[i] will report an error.
Solution:
Change the variable var i declared in the for loop to let i Specific reasons: In the for loop after the first callback function, if you send a request again, the for loop will not stop, even if you write a synchronous request. But if you use let after declaring the for loop variable, the code will not start the next loop until your request is completed and the callback function is executed. This takes into account a closure problem. If you write var and let, the scopes declared are different. Let i will be passed as a local variable Var i will be passed as a global variable If you want to pass the i variable to the next layer, use let to declare. I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website! Recommended reading:Detailed explanation of the use of js injection
What are the common techniques of JS
The above is the detailed content of Detailed explanation of the use of var and let in for loop in jQuery. For more information, please follow other related articles on the PHP Chinese website!