Skip to content

Instantly share code, notes, and snippets.

@juanbrusco
Created April 9, 2019 18:45
Show Gist options
  • Save juanbrusco/9b97778687edc7a87a4668c2a17c8722 to your computer and use it in GitHub Desktop.
Save juanbrusco/9b97778687edc7a87a4668c2a17c8722 to your computer and use it in GitHub Desktop.
Object array iteration - Javascript
// Método Array#forEach
var miArray = [ 2, 4, 6, 8, 10 ];
miArray.forEach( function(valor, indice, array) {
console.log("En el índice " + indice + " hay este valor: " + valor);
});
// Método Object#keys combinado con Método Array#forEach
var obj = {
first: "John",
last: "Doe"
}
// ES6
Object.keys(obj).forEach(key => console.log(key, obj[key]))
// ES5
Object.keys(obj).forEach(function(key) {
console.log(key, obj[key])
})
// Bucle for-i
var miArray = [ 2, 4, 6, 8, 10 ];
for (var i = 0; i < miArray.length; i+=1) {
console.log("En el índice '" + i + "' hay este valor: " + miArray[i]);
}
// Bucle for-in
var miArray = [ 2, 4, 6, 8, 10 ];
for (var indice in miArray) {
console.log("En el índice '" + indice + "' hay este valor: " + miArray[indice]);
}
var miObjeto = { "marca":"audi", "edad":2 };
for (var propiedad in miObjeto) {
if (miObjeto.hasOwnProperty(propiedad)) {
console.log("En la propiedad '" + propiedad + "' hay este valor: " + miObjeto[propiedad]);
}
}
// Bucle for-of
var miArray = [ 2, 4, 6, "hola", "mundo" ];
for (var valor of miArray) {
console.log("Valor: " + valor);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment