O carinha spread nos permite extrair/expandir dados de um array agilizando a nossa vida. Confuso? Acho que não consegui explicar. Vamos à prática. Imaginemos os seguintes arrays:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let mortalKombat = ['Scorpion', 'Sub Zero', 'Liu Kang']; | |
let newCharacters = ['Reptile', 'Kitana']; |
Se tivéssemos que adicionar os novos lutadores ao array principal, poderíamos tentar algo assim:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
mortalKombat.push(newCharacters); | |
console.log(mortalKombat); | |
// ['Scorpion', 'Sub Zero', 'Liu Kang', ['Reptile', 'Kitana']] |
Adicionou mas não ficou do jeito que queríamos. Teríamos então que tratar isso antes, algo mais ou menos assim:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
newCharacters.forEach(function(fighter) { | |
mortalKombat.push(fighter); | |
}); | |
console.log(mortalKombat); | |
// ['Scorpion', 'Sub Zero', 'Liu Kang', 'Reptile', 'Kitana'] |
O operador spread chega chutando a porta e deixando tudo bonitão.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
mortalKombat.push(...newCharacters); | |
console.log(mortalKombat); | |
// ['Scorpion', 'Sub Zero', 'Liu Kang', 'Reptile', 'Kitana'] |
Aqui você encontra um JS Bin com os exemplos acima.