for (var 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)
})
}
}
第二次輸出的是$remove
#或告訴我怎樣在.then裡獲取到key
高洛峰2017-05-19 10:22:43
這個問題是比較典型的循環變數作用域的問題。 then()
中的回调被调用的时候 key
可能已经循环到最后一个了(也可能是间的某个值),所以里面使用的 key
值是当时的 key
值。这在 ES6 中要可以用 let
代替 var
來解(因為我看你已經用 ES6 的箭頭函數,所以先用 ES6)
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}`);
});