Spread Operator
Pode ser utilizado para juntar todos os elementos recebidos em um só array.
-
Resumo/Informações
-
Spread Operator
The spread operator is a convinient way to expand elements of an array in places like arguments and function calls.
We are going to use the apply method, which receives an arrray and it calls the function that the apply method is used on using the elements of the array as the arguments.
function addFourAges (a, b, c, d) {
return a + b + c + d;
}
var sum1 = addFourAges(18, 30, 12, 21);
console.log(sum1); 81
ES5
var ages = [18, 30, 12, 21];
var sum2 = addFourAges.apply(null, ages); primeiro tem que passar a this variable, porém como nesse caso não importa, ela está como null
The apply method will call de addFourAges function and pass the elements of the array on the age variable as the arguments.
81
ES6
const sum3 = addFourAges(...ages); ... is the spread operator. It expands the array into it's components. This is exactly the same of writing 18, 30, 12, 21.
81
Another example
const familySmith = ['John', 'Jane', 'Mike'];
const familyNewbie = ['Bob, 'Bete', 'Mika'];
Now to join these arrays, we can use the spread operator:
const bigFamily = [...familySmith, familyMiller]; This will receive all the elements of both arrays and combine them
console.log(bigFamily); ["John", "Jane", "Mike", "Bob", "Bete", "Mika"]
or
const bigFamily = [...familySmith, 'Lily', familyMiller];
console.log(bigFamily); ["John", "Jane", "Mike", "Lily", "Bob", "Bete", "Mika"]
-
Spread Operator on a nodelist
A node list is what returns from the querySelectorAll.
Changing the color of all the elements (boxes) to Purple.
const h = document.querySelector('h1');
const boxes = document.querySelectorAll('box');
const all = [h, ...boxes]; h is just a node, boxes is a node list because of querySelectorAll
Array.from(all).forEach(cur => cur.style.color = 'purple');