À priori, utiliser une variable globale dans une boucle Javascript forEach
ne pose aucun problème.
1 2 3 |
for(let n = 1; n < 4; n++) { arr.forEach(i => console.log(`${i} + ${n} = ${i + n}`)); } |
donnera
1 2 3 4 5 6 7 8 9 10 11 12 |
1 + 1 = 2 2 + 1 = 3 3 + 1 = 4 4 + 1 = 5 1 + 2 = 3 2 + 2 = 4 3 + 2 = 5 4 + 2 = 6 1 + 3 = 4 2 + 3 = 5 3 + 3 = 6 4 + 3 = 7 |
Le problème
Si l’on utilise jshint, tel que grunt-jshint
avec Grunt
, cela déclenchera une erreur, et Grunt
ne pourra finir le travail :
1 2 3 4 5 |
Running "jshint:summary" (jshint) task assets/js/summary.js 102 | arr.forEach(i => console.log(`${i} + ${n} = ${i + n}`)); ^ Functions declared within loops referencing an outer scoped variable may lead to confusing semantics. (console, n) |
La solution
On intervertit l’ordre des boucles, en plaçant la bouche for
à l’intérieur de la boucle forEach
.
1 2 3 4 5 |
arr.forEach(el => { for(let i = 1; i < 4; i++) { console.log(`${i} + ${n} = ${i + n}`); } }); |
Et là, cela passe nickel le contrôle jshint
. Et hop, on peut continuer le développement.