-1

when i want to get the array value its becomes undefined. what i am doing worng and how to fix it?

var cars = [4, 8];
for (i = 0; i < cars.length; i++) {

  fetch("http://example.com?id=" + cars[i], {
      "credentials": "include",
      "headers": {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0",
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
        "Accept-Language": "en-US,en;q=0.5",
        "Upgrade-Insecure-Requests": "1",
        "Cache-Control": "max-age=0"
      },
      "method": "GET",
      "mode": "cors",
    })

    .then(response => response.text())
    .then(str => {
      var text = str.split('yesyes')[1];
      var abc = text.split('nono')[0];
      document.write(abc + " = " + cars[i]);
    })
}
Jaromanda X
  • 53,868
  • 5
  • 73
  • 87
  • 4
    Use `for (let i = 0..` instead of `for (i = 0..` – Titus Jan 26 '20 at 00:58
  • 2
    1) also give an example response, we don't know what the response look like. 2) you shouldn't use `document.write` especially not after the page have loaded – Endless Jan 26 '20 at 01:00
  • Both comments above are correct. Just an explanation about the `let`. When you declare a variable without `var` or `let`, it becomes global. Which means that at the end of the loop, `i` is equal to `cars.length` (`2`), and then, because your code is asynchronous, when you read `cars[i]` inside your `document.write`, you're reading `cars[2]`, which is undefined. Always scope your variables. In a `for` loop, either use `let`, or use `var` and a closure (@Grey Chanel's answer) – blex Jan 26 '20 at 01:08
  • Use a value of i: `cars[+i] ` – Maksim Tikhonov Jan 26 '20 at 01:14
  • [let] solved the problem. thank you all. – johns abraham Jan 26 '20 at 01:18

1 Answers1

-2

It's about closure. Try this:

for (var i = ...) {
  (function (x) {
    fetch("..." + cars[x], ... 
  })(i);
}
Grey Chanel
  • 212
  • 1
  • 5