Dies ist eine experimentelle Technologie
Da diese Technologie noch nicht definitiv implementiert wurde, sollte die Browserkompatibilität beachtet werden. Es ist auch möglich, dass die Syntax in einer späteren Spezifikation noch geändert wird.
Die flatMap()
Methode bildet jedes Element über eine Funktion ab und flacht das Ergebnis in ein Array ab. Sie ist identisch zu einem map gefolgt von einem flat der Tiefe 1, aber flatMap
ist oft nützlich und beide in einer Methode zusammenführen ist etwas effizienter.
{{EmbedInteractiveExample("pages/js/array-flatmap.html")}}
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
Syntax
var new_array = arr.flatMap(function callback(currentValue[, index[, array]]) { // return element for new_array }[, thisArg])
Parameter
callback
- Funktion, die ein Element für das neue Array erzeugt, welche drei Argumente hat:
currentValue
- Das aktuelle Element, das im Array verarbeitet wird.
index
Optional- Der Index des aktuell zu verarbeitende Elements in dem Array.
array
Optional- Das Array, auf dem
flatMap
aufgerufen wurde.
thisArg
Optional- Wert, der bei der Ausführung von
callback
fürthis
genutzt wird.
Rückgabewert
Ein neues Array mit jedem Element, dass aus dem Resultat der callback Funktion hervorgeht und auf die Tiefe 1 abgeflacht wurde.
Beschreibung
Siehe auf der Seite Array.prototype.map()
für eine detaillierte Beschreibung der callback
Funktion. Die flatMap
Methode ist identisch zu map
gefolgt von flat
mit der Tiefe 1.
Beispiele
map
und flatMap
var arr1 = [1, 2, 3, 4];
arr1.map(x => [x * 2]);
// [[2], [4], [6], [8]]
arr1.flatMap(x => [x * 2]);
// [2, 4, 6, 8]
// only one level is flattened
arr1.flatMap(x => [[x * 2]]);
// [[2], [4], [6], [8]]
Alternative
reduce
und concat
var arr1 = [1, 2, 3, 4];
arr1.flatMap(x => [x * 2]);
// ist equivalent zu
arr1.reduce((acc, x) => acc.concat([x * 2]), []);
// [2, 4, 6, 8]
Spezifikationen
Spezifikation | Status | Kommentar |
---|---|---|
Array.prototype.flatMap proposal |
Candidate (3) |
Browserkompatibilität
BCD tables only load in the browser