La méthode JavaScript Array map () crée un nouveau tableau avec les résultats de l'appel d'une fonction pour chaque élément du tableau.
La syntaxe de la map()
méthode est:
arr.map(callback(currentValue), thisArg)
Ici, arr est un tableau.
Paramètres de map ()
La map()
méthode prend en compte:
- callback - La fonction appelée pour chaque élément du tableau. Ses valeurs de retour sont ajoutées au nouveau tableau. Il prend en:
- currentValue - L'élément actuel transmis depuis le tableau.
- thisArg (facultatif) - Valeur à utiliser comme
this
lors de l'exécution du rappel. Par défaut, c'est le casundefined
.
Valeur renvoyée par map ()
- Renvoie un nouveau tableau avec des éléments comme valeurs de retour de la
callback
fonction pour chaque élément.
Remarques :
map()
ne modifie pas la matrice d'origine.map()
s'exécutecallback
une fois pour chaque élément du tableau dans l'ordre.map()
ne s'exécute pascallback
pour les éléments de tableau sans valeurs.
Exemple 1: mappage d'éléments de tableau à l'aide d'une fonction personnalisée
const prices = (1800, 2000, 3000, 5000, 500, 8000); let newPrices = prices.map(Math.sqrt); // ( 42.42640687119285, 44.721359549995796, 54.772255750516614, // 70.71067811865476, 22.360679774997898, 89.44271909999159 ) console.log(newPrices); // custom arrow function const string = "JavaScript"; const stringArr = string.split(''); // array with individual string character let asciiArr = stringArr.map(x => x.charCodeAt(0)); // map() does not change the original array console.log(stringArr); // ('J', 'a', 'v', 'a','S', 'c', 'r', 'i', 'p', 't') console.log(asciiArr); // ( 74, 97, 118, 97, 83, 99, 114, 105, 112, 116 )
Production
(42.42640687119285, 44.721359549995796, 54.772255750516614, 70.71067811865476, 22.360679774997898, 89.44271909999159) ('J', 'a', 'v', 'a', 'S', 'c', 'r', 'S', 'c', 'r' p 't') (74, 97, 118, 97, 83, 99, 114, 105, 112, 116)
Exemple 2: map () pour les éléments d'objets dans un tableau
const employees = ( ( name: "Adam", salary: 5000, bonus: 500, tax: 1000 ), ( name: "Noah", salary: 8000, bonus: 1500, tax: 2500 ), ( name: "Fabiano", salary: 1500, bonus: 500, tax: 200 ), ( name: "Alireza", salary: 4500, bonus: 1000, tax: 900 ), ); // calculate the net amout to be given to the employees const calcAmt = (obj) => ( newObj = (); newObj.name = obj.name; newObj.netEarning = obj.salary + obj.bonus - obj.tax; return newObj; ); let newArr = employees.map(calcAmt); console.log(newArr);
Production
((nom: 'Adam', netEarning: 4500), (nom: 'Noah', netEarning: 7000), (nom: 'Fabiano', netEarning: 1800), (nom: 'Alireza', netEarning: 4600))
Remarque : map()
assigne undefined
au nouveau tableau si la callback
fonction renvoie undefined
ou rien.
Lecture recommandée: filtre JavaScript Array ()