Home > Web Front-end > JS Tutorial > How to use for loop var and let in jQuery

How to use for loop var and let in jQuery

php中世界最好的语言
Release: 2018-06-02 14:12:16
Original
1567 people have browsed it

This time I will show you how to use the for loop var and let in jQuery, and what are the precautions for using the for loop var and let in jQuery. The following is a practical case, let's take a look.

When sending a request using AJAX, another AJAX request was nested. It was found that the loop variable i in the first success could not be obtained in the success of the inner request. 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: &#39;GET&#39;,
          async: false,
          dataType: &#39;jsonp&#39;,
          contentType: &#39;application/json; charset=utf-8&#39;,
          url: "///////////////////////////////////",
          success: function (result) {
            console.log(rs[i]) //报错
          }
        })
      }
    }
  })
Copy after login


In the 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:

How to use the image display plug-in highslide.js in jQuery

How to use Angularjs custom instructions

The above is the detailed content of How to use for loop var and let in jQuery. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template