Destructuring Arrays, Rest and Spread Operators
Destructuring Arrays
Section titled “Destructuring Arrays”Wenn man einen Wert aus einem Array (oder einem Objekt, siehe dort) benötigt, deklariert man normalerweise eine Variable und weist ihr ein Element dieses Arrays zu.
const fruitBasket = ['apple', 'banana', 'lemon'];const apple = fruitBasket[0];Der Destructuring-Prozess kürzt die Sache etwas ab:
const fruitBasket = ['apple', 'banana', 'lemon'];const [apple, banana] = fruitBasket;
// die erste destrukturierte Variable ist immer das erste Element im Array// die zweite das zweite Element und so weiterconsole.log(apple); // appleconsole.log(banana); // bananaWerden mehr Elemente destrukturiert als der Array Elemente beinhaltet, sind die überschüssigen Elemente einfach undefined.
const fruitBasket = ['apple', 'banana'];const [apple, banana, lemon] = fruitBasket;
console.log(lemon); // undefinedArray Spread
Section titled “Array Spread”Der Array Spread Operator “breitet” eine kommagetrennte Liste aus:
const array = [1, 2, 3, 4, 5];
console.log(array);> Array(5) [1, 2, 3, 4, 5]
console.log(...array);> 1 2 3 4 5
const names = ['Pedro', 'Axi', 'Bibs'];function logNames(name1, name2, name3) { console.log(name1); console.log(name2); console.log(name3);}// spreading arrays as arguments:logNames(...names);// spreading arrays into arrays:// + substitute for concat!const array2 = [1, 2, 3, ...names];console.log(...array2);// substitute for Array.fromconst items = document.querySelectorAll('.item');const arrayFromItems = Array.from(items);const arrayFromSpread = [...items];Array Rest Operator
Section titled “Array Rest Operator”Gegenteil von Spread
// Funktion mit vielen Argumenten:// Der Rest Operator packt Items in ein Arrayfunction logNames2(...names) { names.forEach(name => console.log(name));}logNames2('Bib', 'Axi', 'Pedro', 'George', 'Pye', 'Zack', 'Cloud');
// Array Rest and Destructuringconst scores = [100, 99, 98];const [first, ...restOfScores] = scores;console.log(scores);console.log(first);console.log(restOfScores);