folder check



  • through jquery checks for a folder

    for (var i=1;i<=100;i++){
        $.post( "http://192.168.100.67/vtnuft/group"+i+"/check.php", function(response){
          response = JSON.parse(response);
          $.each(response, function( key, val ) {
              if(key === "check" && val === true){
                  console.log(key,val,i);
                    informationArray.push(i);}
              else if(key === "check" && val === false){
                  console.log(i,"false");
              }
          });
        });  
    }
    

    But informationArray keeps 101 times as long as it's found a whisper. _

    What's the reason for this?



  • Problem is, you use the same variable i in every circuit that changes. In order to preserve the variable &apos; s importance, a new context must be created by calling for an anonymous function.

    This is one way:

    for (var i=1; i<=100; i++)
      !function(i) {
        // $.post(... и т.д.
      }(i);
    

    What kind of magic is going on here?

    function(i) { ... } - this is an anonymous function that receives a parameter i♪ This parameter covers the external variable. i

    function(i) { ... }(i) - it's a challenge to the declared anonymous function, with the variable value transferred to it. i Like a parameter. Now inside the function of the parameter i equal to the value of the variable i at the time of the call. Now the cycle can go further, the variable value i change by 101, but within an anonymous function, the parameter value i It's not gonna change.

    !function(i) { ... }(i) - it's one way to write the last version so the interpreter understands it's an expression. The point is, if the line begins with the word function - The interpreter will consider it to be a specific function, and there will be a syntax error. To avoid this, any operation is added to the expression.

    Such design options are also acceptable:

    • ~function(i) { ... }(i)
    • +function(i) { ... }(i)
    • -function(i) { ... }(i)
    • 1/function(i) { ... }(i)
    • (function(i) { ... })(i)
    • (function(i) { ... }(i))

    Another option is to take the anonymous function not of the whole cycle body, but only of the reversal challenge to be transmitted $.post:

    for (var i=1; i<=100; i++)
      $.post("http://192.168.100.67/vtnuft/group"+i+"/check.php", function (i) {
        return function (responce) {
          // ...
        }
      }(i))
    

    There's an anonymous function that's not at the very beginning of the line, and that's why there's no need for any tricks. Choose the option you like.




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2