I have an array of URLs, and an array of data that I'm pulling externally. The URLs and the data correspond one to one perfectly. I try to do this:
for (var i = 0; i < children.length; i++) {
urls.push(children[i].data.url);
}
for (var i = 0; i < children.length; i++) {
$.ajax({
url: DATA_SOURCE,
dataType: "jsonp",
success: function (data2) {
console.log(urls[0]);
console.log(urls[i]);
}
});
}
The first log always prints the first element of the urls
array. I can change the number to any other valid index and it works. The second log however always prints undefined
. I initially grabbed urls from within the second loop, but I took it out just in case it turned out to be an asynchronous error or something. urls
is initialized to be an Array
, not an Object
. Taking the second log out of the success function (and into the main scope of the for loop) makes it perform as expected. I'd be happy to chalk it up to the ajax request screwing it up somehow, but then why does the first log perform as expected?
Any ideas?