In VBA, it is very useful to be able to enumerate through a collection of objects. In javaScript, there are no collections, everything is a quasi object and there are is no forEach concept.
JavaScript does have this, and a bunch of great advanced array loops
for (key in object) { do something with key (the property name), object[key] (its value) }
which would iterate through every property of object and return its name, but that’s not the same thing as the VBA forEach.
To illustrate this, we are going to use a javaScript implementation of a VBA collection. Let’s say that we have a collection as follows, and we then add things to it.
var co = new collection();
Typically, in VBA we would use
for each x in co
do something with x
next x
Since neither the collection object, nor the for.each construct exist in javaScript, we have to simulate this as a method of the collection class, so it can be called as per the following pattern.
co.forEach( function (x) { do something with x } );
First, in the collection class, I have implemented a method called forEach()
this.forEach = function(yourFunction) {
for (var i = 0 ; i
function (cItem,cIndex) {...}
and pass it as an argument to forEach(). The forEach() method then calls back this anonymous function for every item in the collection, passing a couple of arguments, one of which is the current item in the collection as we pass through it. You then simply process the item as you would have done inside the VBA forEach loop.bruce mcpherson is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://www.mcpher.com. Permissions beyond the scope of this license may be available at code use guidelines