JavaScript Anfänger

Arrays mit Schleifen durchlaufen

Arrays mit Schleifen durchlaufen

Arrays und Schleifen gehören zusammen wie Kaffee und Keks. In diesem Tutorial lernst du alle Methoden, um Arrays zu durchlaufen - und wann du welche verwendest.

Die klassische for-Schleife

Die traditionelle Methode mit Index:

const fruechte = ["Apfel", "Banane", "Orange", "Mango"];

for (let i = 0; i < fruechte.length; i++) {
    console.log(fruechte[i]);
}

// Ausgabe:
// Apfel
// Banane
// Orange
// Mango

Mit Index arbeiten

const namen = ["Anna", "Ben", "Clara"];

for (let i = 0; i < namen.length; i++) {
    console.log(`${i + 1}. ${namen[i]}`);
}

// Ausgabe:
// 1. Anna
// 2. Ben
// 3. Clara

Rückwärts durchlaufen

const zahlen = [1, 2, 3, 4, 5];

for (let i = zahlen.length - 1; i >= 0; i--) {
    console.log(zahlen[i]);
}

// Ausgabe: 5, 4, 3, 2, 1

Jeden zweiten Eintrag

const buchstaben = ["a", "b", "c", "d", "e", "f"];

for (let i = 0; i < buchstaben.length; i += 2) {
    console.log(buchstaben[i]);
}

// Ausgabe: a, c, e

for…of - Die moderne Methode

for...of ist die empfohlene Methode wenn du nur die Werte brauchst:

const fruechte = ["Apfel", "Banane", "Orange", "Mango"];

for (const frucht of fruechte) {
    console.log(frucht);
}

// Ausgabe:
// Apfel
// Banane
// Orange
// Mango

Vorteile von for…of

// Kürzer und lesbarer
for (const item of array) {
    // Kein i++, kein array[i], kein .length
}

// Funktioniert mit allem Iterierbaren
const text = "Hallo";
for (const buchstabe of text) {
    console.log(buchstabe); // H, a, l, l, o
}

Mit Index: entries()

Wenn du den Index brauchst:

const tiere = ["Hund", "Katze", "Vogel"];

for (const [index, tier] of tiere.entries()) {
    console.log(`${index}: ${tier}`);
}

// Ausgabe:
// 0: Hund
// 1: Katze
// 2: Vogel

for…in - Für Objekt-Eigenschaften

Achtung: for...in ist für Objekte gedacht, nicht für Arrays!

// ❌ Nicht empfohlen für Arrays
const arr = ["a", "b", "c"];
for (const i in arr) {
    console.log(i);     // "0", "1", "2" (Strings!)
    console.log(arr[i]); // "a", "b", "c"
}

// ✅ Richtig: for...in für Objekte
const person = { name: "Max", alter: 25, stadt: "Berlin" };
for (const key in person) {
    console.log(`${key}: ${person[key]}`);
}

// Ausgabe:
// name: Max
// alter: 25
// stadt: Berlin

forEach - Die Array-Methode

forEach ist eine Array-Methode mit Callback:

const zahlen = [1, 2, 3, 4, 5];

zahlen.forEach(function(zahl) {
    console.log(zahl * 2);
});

// Ausgabe: 2, 4, 6, 8, 10

Mit Arrow Function

const zahlen = [1, 2, 3, 4, 5];

zahlen.forEach(zahl => console.log(zahl * 2));

// Ausgabe: 2, 4, 6, 8, 10

Mit Index und Array

const fruechte = ["Apfel", "Banane", "Orange"];

fruechte.forEach((frucht, index, array) => {
    console.log(`${index + 1}/${array.length}: ${frucht}`);
});

// Ausgabe:
// 1/3: Apfel
// 2/3: Banane
// 3/3: Orange

forEach vs. for…of

// forEach - kann NICHT mit break/continue
// forEach - kann NICHT await verwenden

const zahlen = [1, 2, 3, 4, 5];

// ❌ break funktioniert NICHT in forEach
zahlen.forEach(zahl => {
    if (zahl === 3) break;  // SyntaxError!
});

// ✅ break funktioniert in for...of
for (const zahl of zahlen) {
    if (zahl === 3) break;  // OK!
    console.log(zahl);
}

Vergleich aller Methoden

MethodeIndex?break/continue?Empfohlen für
forIndex-Kontrolle, komplexe Logik
for...ofMit entries()Standard-Iteration
for...in✅ (als String)Objekte, NICHT Arrays
forEachEinfache Operationen

Praktische Beispiele

Summe berechnen

const preise = [19.99, 5.50, 12.00, 8.75];

// Mit for
let summe1 = 0;
for (let i = 0; i < preise.length; i++) {
    summe1 += preise[i];
}

// Mit for...of
let summe2 = 0;
for (const preis of preise) {
    summe2 += preis;
}

// Mit forEach
let summe3 = 0;
preise.forEach(preis => {
    summe3 += preis;
});

console.log(summe1, summe2, summe3); // Alle: 46.24

Maximum finden

const zahlen = [34, 12, 89, 45, 23, 67];

let max = zahlen[0];

for (const zahl of zahlen) {
    if (zahl > max) {
        max = zahl;
    }
}

console.log("Maximum:", max); // 89

Element suchen

const namen = ["Anna", "Ben", "Clara", "David", "Eva"];
const gesucht = "Clara";

// Mit for...of und break
let gefunden = false;
for (const name of namen) {
    if (name === gesucht) {
        gefunden = true;
        break;
    }
}

console.log(gefunden ? "Gefunden!" : "Nicht gefunden");

Array filtern (manuell)

const zahlen = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const geradeZahlen = [];

for (const zahl of zahlen) {
    if (zahl % 2 === 0) {
        geradeZahlen.push(zahl);
    }
}

console.log(geradeZahlen); // [2, 4, 6, 8, 10]

Array transformieren (manuell)

const namen = ["anna", "ben", "clara"];
const grossgeschrieben = [];

for (const name of namen) {
    grossgeschrieben.push(name.toUpperCase());
}

console.log(grossgeschrieben); // ["ANNA", "BEN", "CLARA"]

Verschachtelte Arrays

const matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

// Alle Elemente ausgeben
for (const zeile of matrix) {
    for (const zelle of zeile) {
        console.log(zelle);
    }
}

// Mit Index
for (let i = 0; i < matrix.length; i++) {
    for (let j = 0; j < matrix[i].length; j++) {
        console.log(`matrix[${i}][${j}] = ${matrix[i][j]}`);
    }
}

Summe einer Matrix

const matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

let summe = 0;

for (const zeile of matrix) {
    for (const zahl of zeile) {
        summe += zahl;
    }
}

console.log("Summe:", summe); // 45

Array von Objekten

const produkte = [
    { name: "Laptop", preis: 999 },
    { name: "Maus", preis: 29 },
    { name: "Tastatur", preis: 79 },
    { name: "Monitor", preis: 349 }
];

// Alle Produkte ausgeben
for (const produkt of produkte) {
    console.log(`${produkt.name}: ${produkt.preis}€`);
}

// Gesamtpreis berechnen
let gesamt = 0;
for (const produkt of produkte) {
    gesamt += produkt.preis;
}
console.log(`Gesamt: ${gesamt}€`); // 1456€

// Produkte über 100€
console.log("Teure Produkte:");
for (const produkt of produkte) {
    if (produkt.preis > 100) {
        console.log(`- ${produkt.name}`);
    }
}

Häufige Muster

Erstes Element finden

const zahlen = [4, 7, 12, 3, 9, 15];

let erstesGrosseAlsZehn = null;

for (const zahl of zahlen) {
    if (zahl > 10) {
        erstesGrosseAlsZehn = zahl;
        break;
    }
}

console.log(erstesGrosseAlsZehn); // 12

Prüfen ob alle/einige

const noten = [2, 1, 3, 2, 1];

// Alle bestanden? (Note <= 4)
let alleBestanden = true;
for (const note of noten) {
    if (note > 4) {
        alleBestanden = false;
        break;
    }
}

// Mindestens einer mit 1?
let hatEinser = false;
for (const note of noten) {
    if (note === 1) {
        hatEinser = true;
        break;
    }
}

console.log("Alle bestanden:", alleBestanden); // true
console.log("Hat Einser:", hatEinser);         // true

Zählen

const text = "Hallo Welt, wie geht es dir heute?";
const buchstaben = text.split("");

let vokale = 0;
const vokalListe = "aeiouäöüAEIOUÄÖÜ";

for (const buchstabe of buchstaben) {
    if (vokalListe.includes(buchstabe)) {
        vokale++;
    }
}

console.log(`Anzahl Vokale: ${vokale}`); // 12

Performance-Tipp

Bei sehr großen Arrays kann die klassische for-Schleife minimal schneller sein:

const grossesArray = new Array(1000000).fill(1);

// Schnellste Variante für Performance-kritische Fälle
const len = grossesArray.length;  // length cachen
for (let i = 0; i < len; i++) {
    // ...
}

Aber: In 99% der Fälle ist der Unterschied vernachlässigbar. Bevorzuge Lesbarkeit!

Zusammenfassung

const arr = [1, 2, 3];

// Standard - for...of (empfohlen)
for (const item of arr) { }

// Mit Index - entries()
for (const [i, item] of arr.entries()) { }

// Klassisch - for
for (let i = 0; i < arr.length; i++) { }

// Callback - forEach
arr.forEach(item => { });

// Für Objekte - for...in
for (const key in obj) { }

Übung: Gegeben ist ein Array von Schülern mit Namen und Noten. Berechne den Notendurchschnitt und gib alle Schüler aus, die besser als der Durchschnitt sind!

const schueler = [
    { name: "Anna", note: 2 },
    { name: "Ben", note: 3 },
    { name: "Clara", note: 1 },
    { name: "David", note: 4 },
    { name: "Eva", note: 2 }
];