84669 人が学習中
152542 人が学習中
20005 人が学習中
5487 人が学習中
7821 人が学習中
359900 人が学習中
3350 人が学習中
180660 人が学習中
48569 人が学習中
18603 人が学習中
40936 人が学習中
1549 人が学習中
1183 人が学習中
32909 人が学習中
2 番目の出力は $remove
または、.thenでキーを取得する方法を教えてください
关键字:闭包
用array.map解决会更优雅
闭包了 es6中将var换成let即可
这个问题是比较典型的循环变量作用域的问题。then() 中的回调被调用的时候 key 可能已经循环到最后一个了(也可能是间的某个值),所以里面使用的 key 值是当时的 key 值。这在 ES6 中要可以用 let 代替 var 来解决(因为我看你已经用了 ES6 的箭头函数,所以先用 ES6)
then()
key
let
var
for (let key in arr) { if (arr.hasOwnProperty(key)) { console.log("这一次可以输出key" + key); this.$http.post("/getPaperListByCIdAndTId", { teacherId: window._const.teacherId }).then((res_in) => { console.log("这一次不能输出key" + key); }); } }
如果要写 ES5,可以用个 IIFE 来封局部化 key 值(通过参数传入,所以不会变了)
for (var key in arr) { if (arr.hasOwnProperty(key)) { (function() { console.log("这一次可以输出key" + key); this.$http.post("/getPaperListByCIdAndTId", { teacherId: window._const.teacherId }).then(function(res_in) { console.log("这一次不能输出key" + key); }); })(key); } }
推荐函数式写法,看起来比较简洁,ES6 可以这样干
Object.keys(arr) .filter(key => arr.hasOwnProperty(key)) .forEach(key => { console.log(`这一次可以输出 key:${key}`); this.$http.post("/getPaperListByCIdAndTId", { teacherId: window._const.teacherId }).then(res_in => { console.log(`这一次不能输出 key 才怪:${key}`); }); });
ES2017 还可以用 async,语法更简洁
Object.keys(arr) .filter(key => arr.hasOwnProperty(key)) .forEach(async key => { console.log(`这一次可以输出 key:${key}`); const res_in = await this.$http.post("/getPaperListByCIdAndTId", { teacherId: window._const.teacherId }); console.log(`这一次不能输出 key 才怪:${key}`); });
刚测试了下,是可以的,而且一定要用let而不是var,否则输出的都是最后一个key
关键字:闭包
用array.map解决会更优雅
闭包了 es6中将var换成let即可
这个问题是比较典型的循环变量作用域的问题。
then()
中的回调被调用的时候key
可能已经循环到最后一个了(也可能是间的某个值),所以里面使用的key
值是当时的key
值。这在 ES6 中要可以用let
代替var
来解决(因为我看你已经用了 ES6 的箭头函数,所以先用 ES6)如果要写 ES5,可以用个 IIFE 来封局部化 key 值(通过参数传入,所以不会变了)
推荐函数式写法,看起来比较简洁,ES6 可以这样干
ES2017 还可以用 async,语法更简洁
刚测试了下,是可以的,而且一定要用let而不是var,否则输出的都是最后一个key