for循环遍历键时request回调无法匹配对应键的解决方案求助
问题分析
这是典型的异步回调与循环变量作用域冲突问题:你用var声明的templKeay是函数级作用域变量,循环中所有迭代共享同一个变量引用。当request的异步回调执行时,循环已经全部跑完,templKeay的值会停留在最后一个键上,导致所有回调都输出同一个值。
解决方案
方案1:用let替代var(ES6+推荐)
let是块级作用域,每次循环迭代都会创建独立的变量实例,回调会绑定当前迭代的变量值:
for(lKeay in datheData[theKeay][0]){ let templKeay = lKeay; // 改用let声明 console.log(lKeay); request({uri: datheData[theKeay][0][lKeay], followRedirect: false, followAllRedirects: false}, function (error, res, body) { theCounter++; console.log(res.headers.location + " " + templKeay); // 现在会输出对应迭代的键 }) }
更简洁的写法是直接在循环中用let声明循环变量:
for(let lKeay in datheData[theKeay][0]){ // 循环变量用let声明 console.log(lKeay); request({uri: datheData[theKeay][0][lKeay], followRedirect: false, followAllRedirects: false}, function (error, res, body) { theCounter++; console.log(res.headers.location + " " + lKeay); // 直接使用循环变量即可 }) }
方案2:用立即执行函数(IIFE)创建闭包(兼容ES5及以下)
如果运行环境不支持ES6,用IIFE把当前迭代的键封装到独立作用域中:
for(lKeay in datheData[theKeay][0]){ console.log(lKeay); // 用IIFE捕获当前lKeay的即时值 (function(currentKey) { request({uri: datheData[theKeay][0][currentKey], followRedirect: false, followAllRedirects: false}, function (error, res, body) { theCounter++; console.log(res.headers.location + " " + currentKey); }) })(lKeay); }
方案3:改用forEach遍历(若目标是数组)
你提到对象是JSON数组,若datheData[theKeay][0]是数组类型,用forEach更直观,它的回调函数会自动为每个元素创建独立作用域:
datheData[theKeay][0].forEach(function(value, key) { console.log(key); request({uri: value, followRedirect: false, followAllRedirects: false}, function (error, res, body) { theCounter++; console.log(res.headers.location + " " + key); }) });
内容的提问来源于stack exchange,提问作者C.Unbay
相关产品推荐
相关产品推荐

