1

The program I'm working on has an array with a bunch of web addresses in it, e.g:

var urls = ["http://www.url.com/page1", "http://www.url.com/page2", "http://www.url.com/page3"];

Then I loop through this array in order to run some code based on each web address:

for (var i = 0; i < urls.length; i++) {
    $.get(urls[i], function(response) {
        console.log(urls[i]);
    });

I'm using the $.get to extract data from another page on the site, and my problem is that the console.log shows undefined? Even more strange is that if I pass url[1], or any value as a number into the console.log, then it returns the url from the array is intended?

Furthermore, if I just log the current for loop index like

console.log([i]);

then it just outputs 3, three times.

0

2 Answers 2

1

You need a closure in order to preserve the i variable. The contest of the variable is global, and when the for ends the value is urls.length + 1. Instead, if you close the code in an IIFE you preserve the value of your variable because it gets a function scope.

With modern browsers you may use

let instead of var: declares a block scope local variable, optionally initializing it to a value.

Change:

for (var i = 0; i < urls.length; i++) {
$.get(url[i], function(response) {
    console.log(urls[i]);
});

To:

for (var i = 0; i < urls.length; i++) {
  (function (i) {
      $.get(url[i], function(response) {
          console.log(urls[i]);
      });
  })(i);
Sign up to request clarification or add additional context in comments.

Comments

1

You have an asynchronous issue. When the inner function gets called, i === urls.length because the outer for loop has already finished.

for (var i = 0; i < urls.length; i++) {
    // The anonymous function won't get called until the for loop completes
    // and you get a response back from the url.
    $.get(urls[i], function(response) {
        // When this finally gets called, the for loop has already completed
        // and i === urls.length, AKA undefined
        console.log(urls[i]);
    });
}

You can use let to fix your issue:

for (var i = 0; i < urls.length; i++) {
    // This will scope the variable to this for loop.
    let url = urls[i];
    $.get(url, function(response) {
        console.log(url);
    });
}

1 Comment

or just change var i to let i

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.