Although the 'Array' data type is one of the most commonly used, not all arrays are created equal-at least not among the various JavaScript implementations. Fortunately, Dojo's Array facilities provide an easy-to-use abstraction, ensuring that the code you write will work anywhere, and you won't be left scratching your head staring at a big semantic bug that's painful to track down. Consider the follovving (seemingly innocent) block of code: "l != -1) 1* do something ... '1
Although you might swear that there couldn't possibly be anything wrong with that code, that's because you're probably (again) using and testing it with a nice KHTML- or Gecko-based browser. The Trident-based Internet Explorer has its own notions of what an Array should and shouldn't do, and the indexOj method isn't one of them. In other words, your code will most likely fail outright if you try to invoke the indexOjfunction on an Array when the code runs in IE. In this particular case, you could use the dojo. indexOjfunction to safely produce code that is portable across browsers:
var a = getMetasyntacticVariables () ; if (dojo.indexOf(a, "foo") != -11 I 1* do something ... *1
Other useful Array methods available via the dojo. * namespace include map, filter, every, some, lastIndexOj andjorEach. They all work as described in the Mozilla developer documentation.
At first glance, thejorEach method may seem a bit redundant, because JavaScript provides ajor loop construct, butjorEach provides one particularly important feature that often escapes even many senior-level JavaScript prograrruners: block level scope. To illustrate this, first consider the following two approaches to iterating over an Array:
I I Approach 1:
var arr = getSomeArray (I ; for (var i in arr) I
/* manipulate arr[i] */
1* The last value of i is available here because the for loop does not have its own block level scope. Ditto for any temporary variables
defined between the braces. * I
var arr = getSomeArray () i
dojo. forEach (arr, function (item) 1* manipulate item *1
/* Neither item nor any temporary variables are available here because the scope of the anonymous function protected this outer scope from it. */




Reply With Quote
Bookmarks