[数组值在使用fetch [duplicate]之后变得未定义

问题描述 投票:0回答:1

当我想获取数组值时,它变得不确定。我在做什么以及如何解决?

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]);
    })
}
javascript arrays for-loop fetch undefined
1个回答
0
投票

关于关闭。试试这个:

for (var i = ...) {
  (function (x) {
    fetch("..." + cars[x], ... 
  })(i);
}
© www.soinside.com 2019 - 2024. All rights reserved.