Skip to content

To $.each his own

In JavaScript, there is no iterator over arrays or objects. One has to do a for construct such as the one below. Notice how one has to declare all the variables with var to prevent global namespace pollution. And there is a lot of verbiage just to iterate over these objects.

var row, cell, type, matRow, symbolRow, rl, ml, symChar, ch;
ml = mat.length;
for (row=0; row <=ml, row++){
     matRow = mat[row];
     for (type in matRow) {
         symbolRow = matRow[type];
         rl = symbolRow.length;
         for (cell=0; cell <= rl; rl++){
             symChar = symbolRow[cell];
             ch = symChar[0];

A better way can be done with jQuery (or write one’s own custom iterator–not hard to do in this language):

$.each(mat, function(row, matRow){
    $.each(matRow, function(type, symbolRow){
        $.each(symbolRow, function (cell, symChar) {
            var ch = symChar[0];

It is iterating over the same stuff applying the function to each item (arrays pass in index, value and objects pass in key, value). This allows one to automatically encapsulate the index, value kinds of variables. With closures, one can easily access variables on the outside of the function.

Good to keep in mind.

P.S. Thanks parkov for pointing me towards syntax highlighting.

Post a Comment

Your email is never published nor shared.