Practical Functions
Many JavaScript frameworks have a large number of practical functions that make it easier to develop applications using JavaScript. This article has a lot to add, so I will discuss one of the more compelling functions in most frameworks.
If you have used JavaScript arrays, you may be very familiar with using loops to iterate the array to operate its values. For example, consider the code in Listing 2:
Listing 2: Traditional Method for iterative JavaScript Array
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 is a little troublesome. Most JavaScript frameworks include the each function, which calls a specific function for each element in the array. Using MooTools, you can use the code in listing 3 to perform the same operations in Listing 2.
Listing 3: using the each function of MooTools
['Apple', 'Banana ', 'Orange']. each (function (item ){
Alert (item );
});
In listing 3, The syntax is the same as Prototype and jQuery, and YUI and ExtJS. are slightly different. However, when a hash or object is applied, different framework syntaxes are different. For example, in MooTools, you can use the following code:
Listing 4: using the each function of MooTools for each object of a 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 looks like the code in listing 5:
Listing 5: Use the each function of Prototype 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 practical functions, including String, Number, Array, Hash, and Date functions. For more information, see the API manual for the JavaScript framework.
Reprint address: http://www.denisdeng.com /? P = 716
Address: http://www.ibm.com/developerworks/web/library/wa-jsframeworks/index.html