Eight Weeks of Prototype: Week 3, Prototype Data Types
Arrays
Prototype automatically extends the array type to give all of the functionality of enumerables. That is, you can you use methods such as each() on any array that you create.
Revisiting Listing 3 (which created a CSS colour string from 3 different variables), we can define the colours as an array then use the invoke() method (covered above) to create the string.
Listing 6 shows an example of doing so. When we call invoke with toColorPart() as the function to execute, an array is returned with each element corresponding to the result for each element in the input array. We can then join this value to create a single string from the returned array.
Listing 6 Using arrays and invoke to create hex colour codes (listing-6.html)
<html> <head> <title>Using arrays and invoke to create hex colour codes</title> <script type="text/javascript" src="/js/prototype.js"></script> </head> <body> <div id="foo"> This div will change colour! </div> <script type="text/javascript"> var colors = [ 255, 100, 0 ]; var hexColors = colors.invoke('toColorPart'); // same as [ 'ff', '64', '00' ] var hex = '#' + hexColors.join(''); // hex will have the value #ff6400 $('foo').setStyle({ backgroundColor : hex }); // or this can be shortened further to: var hex = '#' + colors.invoke('toColorPart').join(''); alert(hex); </script> </body> </html>



