In this recipe we will learn how to use a standard data structure called an Array to store a list of names or values.
To create an array, a storage element that holds a list of values, elements, or objects, we use the raw JavaScript Array object to define a literal array var myarray = [1, 2, 'my 3rd value']
;. In our example, we first declare our array; it is in an empty state, then we call upon either raw JavaScript's push()
array object method or MooTools' extension of the array native include()
, based on the ternary output, to add our string value to the array.
Add items to an array. Allow or disallow the addition of duplicate items with a switch in the form.
<script type="text/javascript" src="mootools-1.3.0.js"></script> </head> <body> <form action="" method="get"> <input type="text" id="myitem"/> Ignore if already in the array? <input type="checkbox" id="unique"/> <input type="button" id="mybutton" value="Add This" onclick="store_item_in_array();"/> </form> <script type="text/javascript"> // declare the array var myarray = []; // an array-dedicated utility function to add elements function store_item_in_array() { // use the $ object to get element with id "myitem" var myitem = $('myitem').value; // ternary operators can save a lot of space var ischecked = $('unique').get('checked'); var unique = (ischecked) ? 1 : 0; if (!unique) { // (A) add an item to an array with raw JavaScript myarray.push(myitem); } else { // (B) add an item to an array, but make it moonique myarray.include(myitem); } alert('Length of Array: '+myarray.length); } </script>
Much like $, arrays are infused with methods that extend their capability. This snippet calls the JavaScript inherent push()
, which post-pends the single argument to the array, like this: var myarray.push('myvalue')
;.
Note
NOTE: The JavaScript array object will hold much more than string values: it can hold integers, objects, even other array objects to create multi-dimensional arrays!
MooTools has further extended the array prototype by adding new, useful methods. The method used here is called include()
, which works identically both in syntax and in function to push()
; however, it adds a duplicate value check to the incoming argument. If one or more values present are matched, the function does not add a value to the array.