Me preguntaba si hay una manera de hacer algo como un bucle PHP foreach
en JavaScript. La funcionalidad que estoy buscando es algo así como este fragmento de PHP:
foreach($data as $key => $value) { }
Estaba mirando el bucle JS for..in
, pero parece que no hay manera de especificar el as
. Si hago esto con un bucle for 'normal' (for(var i = 0; i < data.length; i++
), ¿hay alguna forma de coger los pares clave => valor?
for (var k in target){
if (target.hasOwnProperty(k)) {
alert("Key is " + k + ", value is " + target[k]);
}
}
hasOwnProperty
se utiliza para comprobar si tu target
realmente tiene esa propiedad, en lugar de haberla heredado de su prototipo. Un poco más simple sería:
for (var k in target){
if (typeof target[k] !== 'function') {
alert("Key is " + k + ", value is" + target[k]);
}
}
Sólo comprueba que k
no es un método (ya que si target
es array
te saldrán un montón de métodos alertados, por ejemplo indexOf
, push
, pop
,etc.)