Maison > Questions et réponses > le corps du texte
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
高洛峰2017-05-19 10:22:43
Ce problème est un problème typique de portée de variable de boucle. then()
中的回调被调用的时候 key
可能已经循环到最后一个了(也可能是间的某个值),所以里面使用的 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}`);
});
ringa_lee2017-05-19 10:22:43
Je viens de le tester, ça marche, et vous devez utiliser let au lieu de var, sinon la sortie sera la dernière clé