# 🚀 JavaScript Arrays vs Objects - Vollständige Übersicht ## 📊 Grundlegende Unterschiede | Eigenschaft | **Array** | **Object** | |-------------|-----------|------------| | **Datenstruktur** | Geordnete Liste | Schlüssel-Wert-Paare | | **Indexierung** | Numerisch (0, 1, 2, ...) | String-basierte Schlüssel | | **Reihenfolge** | ✅ Garantiert | ⚠️ Nicht garantiert* | | **Länge** | `.length` Eigenschaft | Keine direkte Länge | | **Iteration** | `for`, `forEach`, `map`, etc. | `for...in`, `Object.keys()` | *\*Moderne JS-Engines bewahren die Reihenfolge, aber es ist nicht garantiert* --- ## 🔧 Syntax-Vergleich ### **Array Deklaration** ```javascript // Verschiedene Wege Arrays zu erstellen const fruits = ['Apple', 'Banana', 'Orange']; const numbers = [1, 2, 3, 4, 5]; const mixed = [1, 'Hello', true, null]; const empty = []; const withConstructor = new Array(5); // Erstellt Array mit 5 leeren Slots ``` ### **Object Deklaration** ```javascript // Verschiedene Wege Objects zu erstellen const person = { name: 'Max', age: 30, city: 'Berlin' }; const empty = {}; const withConstructor = new Object(); const dynamicKey = { [variable]: 'value' }; ``` --- ## 🎯 Zugriff auf Daten ### **Array Zugriff** ```javascript const colors = ['red', 'green', 'blue']; // Zugriff über Index console.log(colors[0]); // 'red' console.log(colors[1]); // 'green' console.log(colors[-1]); // undefined (kein negativer Index) // Destructuring const [first, second] = colors; ``` ### **Object Zugriff** ```javascript const car = { brand: 'BMW', model: 'X5', year: 2023 }; // Dot Notation console.log(car.brand); // 'BMW' // Bracket Notation console.log(car['model']); // 'X5' // Destructuring const { brand, model } = car; ``` --- ## ⚡ Wichtige Methoden ### **Array Methoden** #### **Manipulationsmethoden** ```javascript const arr = [1, 2, 3]; // Hinzufügen arr.push(4); // [1, 2, 3, 4] - am Ende arr.unshift(0); // [0, 1, 2, 3, 4] - am Anfang // Entfernen arr.pop(); // [0, 1, 2, 3] - letztes Element arr.shift(); // [1, 2, 3] - erstes Element // Suchen arr.indexOf(2); // 1 arr.includes(3); // true arr.find(x => x > 1); // 2 ``` #### **Transformationsmethoden** ```javascript const numbers = [1, 2, 3, 4, 5]; // Map - transformiert jedes Element const doubled = numbers.map(x => x * 2); // [2, 4, 6, 8, 10] // Filter - filtert Elemente const even = numbers.filter(x => x % 2 === 0); // [2, 4] // Reduce - reduziert zu einem Wert const sum = numbers.reduce((acc, x) => acc + x, 0); // 15 // Sort - sortiert Array numbers.sort((a, b) => b - a); // [5, 4, 3, 2, 1] ``` ### **Object Methoden** ```javascript const person = { name: 'Anna', age: 25, city: 'Hamburg' }; // Schlüssel und Werte Object.keys(person); // ['name', 'age', 'city'] Object.values(person); // ['Anna', 25, 'Hamburg'] Object.entries(person); // [['name', 'Anna'], ['age', 25], ['city', 'Hamburg']] // Hinzufügen/Ändern person.email = 'anna@example.com'; person['phone'] = '123-456-7890'; // Löschen delete person.city; // Kopieren/Zusammenführen const copy = { ...person }; const merged = Object.assign({}, person, { country: 'Germany' }); ``` --- ## 🔄 Iteration Vergleich ### **Array Iteration** ```javascript const fruits = ['Apple', 'Banana', 'Cherry']; // For-Loop for (let i = 0; i < fruits.length; i++) { console.log(i, fruits[i]); } // For-of (Werte) for (const fruit of fruits) { console.log(fruit); } // forEach fruits.forEach((fruit, index) => { console.log(index, fruit); }); ``` ### **Object Iteration** ```javascript const person = { name: 'Tom', age: 30, city: 'Berlin' }; // For-in (Schlüssel) for (const key in person) { console.log(key, person[key]); } // Object.keys() Object.keys(person).forEach(key => { console.log(key, person[key]); }); // Object.entries() Object.entries(person).forEach(([key, value]) => { console.log(key, value); }); ``` --- ## 📈 Erweiterte Array-Konzepte ### **Mehrdimensionale Arrays** ```javascript // 2D Array (Matrix) const matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]; console.log(matrix[1][2]); // 6 // 3D Array const cube = [ [[1, 2], [3, 4]], [[5, 6], [7, 8]] ]; ``` ### **Array-ähnliche Objekte** ```javascript // Arguments Object (in Funktionen) function example() { console.log(arguments); // Array-ähnlich console.log(Array.from(arguments)); // Echtes Array } // NodeList (DOM) const elements = document.querySelectorAll('div'); const elementsArray = Array.from(elements); ``` ### **Typed Arrays** ```javascript // Für spezielle Datentypen const int8Array = new Int8Array(4); const float32Array = new Float32Array([1.1, 2.2, 3.3]); const uint8Array = new Uint8Array(10); ``` --- ## 🏗️ Erweiterte Object-Konzepte ### **Verschachtelte Objects** ```javascript const company = { name: 'TechCorp', address: { street: 'Hauptstraße 1', city: 'München', country: 'Germany' }, employees: [ { name: 'Max', role: 'Developer' }, { name: 'Lisa', role: 'Designer' } ] }; // Zugriff auf verschachtelte Daten console.log(company.address.city); // 'München' console.log(company.employees[0].name); // 'Max' ``` ### **Object Prototypes** ```javascript // Constructor Function function Person(name, age) { this.name = name; this.age = age; } Person.prototype.greet = function() { return `Hallo, ich bin ${this.name}`; }; const person1 = new Person('Anna', 25); console.log(person1.greet()); // 'Hallo, ich bin Anna' ``` ### **ES6 Classes** ```javascript class Animal { constructor(name, species) { this.name = name; this.species = species; } speak() { return `${this.name} macht Geräusche`; } } class Dog extends Animal { constructor(name, breed) { super(name, 'Hund'); this.breed = breed; } speak() { return `${this.name} bellt!`; } } ``` --- ## 🎨 Praktische Anwendungsfälle ### **Wann Arrays verwenden?** ✅ **Perfekt für:** - Listen von ähnlichen Elementen - Reihenfolge ist wichtig - Numerische Indizierung - Iteration über alle Elemente - Mathematische Operationen ```javascript // Beispiele const todoList = ['Einkaufen', 'Putzen', 'Lernen']; const scores = [85, 92, 78, 95]; const colors = ['#FF0000', '#00FF00', '#0000FF']; ``` ### **Wann Objects verwenden?** ✅ **Perfekt für:** - Strukturierte Daten mit Labels - Konfigurationen - Schlüssel-Wert-Beziehungen - Komplexe Datenstrukturen - APIs und JSON ```javascript // Beispiele const userProfile = { username: 'max123', email: 'max@example.com', preferences: { theme: 'dark', language: 'de' } }; const apiResponse = { status: 'success', data: [...], timestamp: Date.now() }; ``` --- ## ⚠️ Häufige Fallstricke ### **Array Fallstricke** ```javascript // Sparse Arrays (Löcher) const sparse = [1, , , 4]; console.log(sparse.length); // 4 console.log(sparse[1]); // undefined // Array-Mutation const original = [1, 2, 3]; const modified = original.push(4); // Verändert original! console.log(original); // [1, 2, 3, 4] // Besser: Immutable Methoden const newArray = [...original, 4]; ``` ### **Object Fallstricke** ```javascript // Referenz vs Kopie const obj1 = { a: 1 }; const obj2 = obj1; // Referenz! obj2.a = 2; console.log(obj1.a); // 2 (auch verändert!) // Shallow vs Deep Copy const shallow = { ...obj1 }; const deep = JSON.parse(JSON.stringify(obj1)); // Funktioniert nicht immer // Property Enumeration const obj = { a: 1, b: 2 }; Object.defineProperty(obj, 'c', { value: 3, enumerable: false }); console.log(Object.keys(obj)); // ['a', 'b'] - 'c' fehlt! ``` --- ## 🔥 Performance-Tipps ### **Array Performance** ```javascript // Schnell: Direkte Indizierung const value = arr[index]; // Langsam: Lineare Suche const value = arr.find(x => x.id === targetId); // Besser: Map für Lookups const map = new Map(arr.map(item => [item.id, item])); const value = map.get(targetId); ``` ### **Object Performance** ```javascript // Schnell: Direkte Property-Zugriff const value = obj.property; // Langsam: Dynamische Properties const value = obj[computedKey]; // Map für dynamische Keys const map = new Map(); map.set(key, value); ``` --- ## 🛠️ Moderne JavaScript Features ### **Destructuring** ```javascript // Array Destructuring const [first, second, ...rest] = [1, 2, 3, 4, 5]; // Object Destructuring const { name, age, ...others } = person; const { name: userName, age: userAge } = person; // Umbenennung ``` ### **Spread Operator** ```javascript // Arrays const arr1 = [1, 2, 3]; const arr2 = [4, 5, 6]; const combined = [...arr1, ...arr2]; // Objects const obj1 = { a: 1, b: 2 }; const obj2 = { c: 3, d: 4 }; const combined = { ...obj1, ...obj2 }; ``` ### **Optional Chaining** ```javascript // Sicher auf verschachtelte Properties zugreifen const street = person.address?.street; const firstEmployee = company.employees?.[0]?.name; ``` --- ## 📝 Zusammenfassung | Kriterium | Array | Object | |-----------|-------|--------| | **Verwendung** | Geordnete Listen | Strukturierte Daten | | **Zugriff** | Numerischer Index | String-Schlüssel | | **Iteration** | Sehr einfach | Mittels Hilfsmethoden | | **Performance** | Schnell für Listen | Schnell für Lookups | | **Flexibilität** | Weniger flexibel | Sehr flexibel | **💡 Faustregel:** - **Array** für Listen und Sequenzen - **Object** für strukturierte Daten und Konfigurationen