try范围内的变量

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

此代码按预期工作:

for (let i = 0; i < 2; i++) {
  try {
    let id = 'id ' + i;
    const request = fetch('https://httpbin.org/get?a=' + i).then(r => {
      if (r.ok) {
        r.json().then(o => {
          console.log(id);
          console.log('response', o.args.a);
        });
      }
    });
  } catch {}
}

为什么

id
总是等于
1

for (let i = 0; i < 2; i++) {
  try {
    var id = 'id ' + i;
  } catch {}
  try {
    const request = fetch('https://httpbin.org/get?a=' + i).then(r => {
      if (r.ok) {
        r.json().then(o => {
          console.log(id);
          console.log('response', o.args.a);
        });
      }
    });
  } catch {}
}

for (let i = 0; i < 2; i++) {
  try {
    var id = 'id ' + i;
    const request = fetch('https://httpbin.org/get?a=' + i).then(r => {
      if (r.ok) {
        r.json().then(o => {
          console.log(id);
          console.log('response', o.args.a);
        });
      }
    });
  } catch {}
}

javascript scope try-catch
© www.soinside.com 2019 - 2024. All rights reserved.