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)
})
}
}
La deuxième sortie est $remove
Ou dites-moi comment obtenir la clé. Ensuite
Ce problème est un problème typique de portée de variable de boucle. then()
中的回調被調用的時候 key
可能已經循環(huán)到最后一個了(也可能是間的某個值),所以里面使用的 key
值是當時的 key
值。這在 ES6 中要可以用 let
代替 var
pour le résoudre (car je vois que vous avez déjà utilisé les fonctions fléchées de ES6, alors utilisez ES6 en premier)
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);
});
}
}
Si vous souhaitez écrire ES5, vous pouvez utiliser un IIFE pour sceller la valeur de clé localisée (transmise via les paramètres, afin qu'elle ne change pas)
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);
}
}
Méthode d'écriture fonctionnelle recommandée, ?a a l'air plus simple, ES6 peut le faire comme ?a
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 peut aussi utiliser async, la syntaxe est plus concise
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}`);
});
Je viens de le tester, ?a marche, et vous devez utiliser let au lieu de var, sinon la sortie sera la dernière clé