Home / Advanced JavaScript Tutorials / Creating dense arrays |
CodingForums Jump to...
- CSS Drive
- JavaScript Menus - PHP Resources - Hotels & Vacations - Java Online Casinos - Web hosting Search |
A dense array excels over a normal one when it comes to initializing a rather large array with values upon declaration. In this section, we'll create a script that writes out the current date and time, in the following format: Tuesday, July 28, 1998 The obvious task at hand is to first declare a series of variables that store the text "Monday", "Tuesday" etc and "January", "February", etc, since JavaScript is not human, and does not by default understand our calendar system. The remaining work is to match these text with the current date, and write it out. The tedious part is the formal, and the perfect job for arrays to handle- dense arrays, to be precise: var dayarray=new Array("Sunday","Monday","Tuesday", var montharray=new Array("January","February","March","April","May", The above code not only efficiently stores in the days of the week and months of the year values into two arrays, but allows us to directly use the JavaScript prebuilt functions date.getDay() and date.getMonth() as the index to reference the current date as represented by text, and write them out. Let's see just how this is done. The below shows the complete code that outputs the current date and time: <script>
A code that may take a full page to write now has been reduced to one third, thanks to our buddy the dense array. -Tutorial introduction |
http://javascriptkit.com |