forEach goodness.

This morning, I was again reminded about something I am continually forgetting and it’s worth documenting, so here goes:


Not only does dojo.forEach iterate over an array passing the element to a function each time:

var arr = ["one","two","three"];
// print one, two, three
dojo.forEach(arr,function(el){ console.log(el); });

It also passes the current index in the array (which I find uber helpful):

var arrOne = ["a","b","c"];
var arrTwo = ["one","two","three"];
dojo.forEach(arrOne,function(el,idx){
     // better than idx++
     var alt = arrTwo[idx];
     console.log(alt);
});

You can pass a named function, too. forEach automatically passes the element anyway:

var connects = [];
connects.push(dojo.connect("node","onclick",console,"log"));
// later:
dojo.forEach(connects,dojo.disconnect);

It also scopes, making “this” useful:

var foo = {
     myMethod: function(el){
        console.log(el);
     }
};
dojo.forEach(["a","b","c"],function(item){
     this.myMethod(item);
},foo);

And to top it alll off, dojo.query / dojo.NodeList has a .forEach method, which assumes scope, and otherwise
works the same (though the array is each domNode in the results:)

// add some text to all nodes class="links"
dojo.query(".links").forEach(function(n){
      n.innerHTML += " - touched ";
      dojo.connect(n,"onclick",function(e){
            conosle.log(e.target);
      });
});

Hope this helps.

Tags: