Utility functions
Many JavaScript frameworks have a large number of utility functions that make it easier to apply JavaScript to developing applications. There are so many things to add to this article, so I'm going to talk about one of the more compelling functions in most frameworks.
If you've ever used a JavaScript array, you might be familiar with the value of using loops to iterate over an algebraic group operation. For example, consider the code in Listing 2:
Listing 2: The traditional approach to iterative JavaScript arrays
var fruit = [' apple ', ' banana ', ' orange '];
for (var i = 0; i < fruit.length; i++) {
Alert (Fruit[i]);
}
The code in Listing 2 is correct, but it's a bit cumbersome. Most JavaScript frameworks include each feature, which invokes a specific function for each element in the array. Using MooTools, the same action in Listing 2 can be done with the code in Listing 3.
Listing 3: each function with MooTools
[' Apple ', ' banana ', ' orange '].each (function (item) {
alert (item);
});
Listing 3 is syntactically the same as prototype and jquery, YUI and ExtJS. Slightly different. However, when applied to a hash or object, the different framework syntax is different. For example, in MooTools, you can use the code in the following list:
Listing 4: Use the MooTools each function for each object of the key/value pair
var hash = new Hash ({name: "Joe Lennon", Email: "joe@joelennon.ie"});
Hash.each (function (value, key) {
Alert (key + ":" + value);
});
However, using the prototype library, this looks like the code in Listing 5:
Listing 5: Use the prototype each function for each object of the key/value pair
var hash = $H ({name: "Joe Lennon", Email: "joe@joelennon.ie"});
Hash.each (function (pair) {
Alert (Pair.key + ":" + pair.value);
});
Each framework contains many more useful functions, usually divided into string functions, number functions, array functions, hash functions, date functions, and so on. For more information, see the API manual for the relevant JavaScript framework.
Reprint Address: http://www.denisdeng.com/?p=716