La méthode Array . reduce ( ) permet d’appliquer de la même façon un callBack à TOUS les éléments d’un Array, en accummulant le résultat dans un accumulateur qui est le premier paramètre du callBack, le deuxième paramètre étant la valeur...
moreLa méthode Array . reduce ( ) permet d’appliquer de la même façon un callBack à TOUS les éléments d’un Array, en accummulant le résultat dans un accumulateur qui est le premier paramètre du callBack, le deuxième paramètre étant la valeur de l’élément actuel de l’array, et le troisième étant l’index numérique (de 0 à n-1, n étant le nombre d’éléments dans l’array) de l’élément en cours de traitement.
Dans le code qui suit, nous avons utilisé la méthode « Array . reduce ( ) » selon trois algorithmes, et nous avons comparé sa consommation de temps la méthode récursive dans une boucle « do…while ».
En gros, la syntaxe de « Array . reduce ( ) » est la suivante :
const retval =
Array . reduce ( (accu, actu, idx) => callBack, initValue );
Vous pouvez tout aussi mettre la valeur initiale de l’accumulateur comme sa valeur par défaut, au lieu de la mettre à la suite du callBack.
Si vous omettez la valeur initiale de la méthode « Array . reduce () », la valeur du premier élément de l’array sera utilisée comme valeur initiale.
Code source de notre petit programme :
La logique de ce code est la suivante. Le nombre dont on veut calculer la factorielle est utilisé pour définir la taille d’un array. Le troisième paramètre (index des éléments) représentera les différents nombres qui interviennent comme facteurs.