Die JavaScript Array map () -Methode erstellt ein neues Array mit den Ergebnissen des Aufrufs einer Funktion für jedes Array-Element.
Die Syntax der map()
Methode lautet:
arr.map(callback(currentValue), thisArg)
Hier ist arr ein Array.
map () Parameter
Die map()
Methode umfasst:
- Rückruf - Die Funktion, die für jedes Array-Element aufgerufen wird. Die Rückgabewerte werden dem neuen Array hinzugefügt. Es dauert:
- currentValue - Das aktuelle Element, das vom Array übergeben wird.
- thisArg (optional) - Wert, der
this
beim Ausführen eines Rückrufs verwendet werden soll. Standardmäßig ist esundefined
.
Rückgabewert von map ()
- Gibt ein neues Array mit Elementen als Rückgabewerte von der
callback
Funktion für jedes Element zurück.
Anmerkungen :
map()
ändert das ursprüngliche Array nicht.map()
wirdcallback
einmal für jedes Array-Element der Reihe nach ausgeführt.map()
wird nichtcallback
für Array-Elemente ohne Werte ausgeführt.
Beispiel 1: Zuordnen von Array-Elementen mithilfe einer benutzerdefinierten Funktion
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 )
Ausgabe
(42.42640687119285, 44.721359549995796, 54.772255750516614, 70.71067811865476, 22.360679774997898, 89.44271909999159) ('J', 'a', 'v', 'a', 'S', '' ',' ' 't') (74, 97, 118, 97, 83, 99, 114, 105, 112, 116)
Beispiel 2: map () für Objektelemente im Array
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);
Ausgabe
((Name: 'Adam', netEarning: 4500), (Name: 'Noah', netEarning: 7000), (Name: 'Fabiano', netEarning: 1800), (Name: 'Alireza', netEarning: 4600))
Hinweis : map()
Abtretungsempfänger undefined
in das neue Array , wenn die callback
Funktion zurückkehrt undefined
oder nichts.
Empfohlene Lektüre: JavaScript Array Filter ()