Created
September 24, 2019 15:34
-
-
Save parzibyte/c035b223cf9f3a0724e5a8017c8de241 to your computer and use it in GitHub Desktop.
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
/** | |
* Foreach en JavaScript | |
* | |
* @author parzibyte | |
*/ | |
const canciones = [ | |
"Hang onto yourself", | |
"Go your own way", | |
"Modern Love", | |
]; | |
// Primer ejemplo, definiendo una función y luego pasándola a forEach | |
const funcionQueRecorre = function(cancion) { | |
console.log("Tenemos una canción: ", cancion); | |
} | |
canciones.forEach(funcionQueRecorre); | |
// Segundo ejemplo recibiendo el índice, igualmente con una función con nombre | |
const funcionQueRecorreConIndice = function(cancion, indice) { | |
console.log("Tenemos la canción %s en el índice %d", cancion, indice); | |
} | |
canciones.forEach(funcionQueRecorreConIndice); | |
// Tercer ejemplo recibiendo el arreglo | |
const funcionQueRecorreConIndiceYArreglo = function(cancion, indice, arreglo) { | |
console.log("Tenemos la canción %s en el índice %d. El arreglo completo es %s", cancion, indice, arreglo); | |
} | |
canciones.forEach(funcionQueRecorreConIndiceYArreglo); | |
// Cuarto ejemplo con función flecha | |
const funcionFlechaQueRecorreConIndiceYArreglo = (cancion, indice, arreglo) => { | |
console.log("Tenemos la canción %s en el índice %d. El arreglo completo es %s", cancion, indice, arreglo); | |
} | |
canciones.forEach(funcionFlechaQueRecorreConIndiceYArreglo); | |
// Quinto ejemplo, función anónima | |
canciones.forEach(function(cancion) { | |
console.log("Canción dentro de función anónima: ", cancion); | |
}); | |
// Sexto ejemplo, función flecha anónima | |
canciones.forEach(cancion => { | |
console.log("Canción dentro de función flecha anónima: ", cancion); | |
}); | |
// Séptimo ejemplo, función flecha anónima de una línea | |
canciones.forEach(cancion => console.log("Canción dentro de función flecha simplificada y anónima: ", cancion)); | |
// Octavo ejemplo, invocando a función | |
canciones.forEach(console.log); | |
// Noveno ejemplo, se puede recorrer cualquier arreglo | |
const personas = [{ | |
nombre: "Luis", | |
edad: 23, | |
}, | |
{ | |
nombre: "John Galt", | |
edad: 50 | |
} | |
]; | |
personas.forEach(persona => { | |
console.log("Nombre: %s, edad: %d", persona.nombre, persona.edad); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment