Javascript’s foreach

Javascript doesn’t have foreach statement, but it’s simple to emulate one:

<script type="text/javascript">
var arr = ['one', 'two', 'three', 'four', 'five', 'etc'];
for (var i in arr) {
	var element = arr[i];
	alert(i + ': ' + element);
}
</script>

It’s actually equivalent of foreach in other languages like PHP.
If you have jQuery on your webpage you can use jQuery’s foreach:

<script type="text/javascript">
var arr = ['one', 'two', 'three', 'four', 'five', 'etc'];
jQuery.each(arr, function(index, element) {
	alert(index + ': ' + element);
});
</script>

Books to read

Comments are closed.