官术网_书友最值得收藏!

Storing a list of names in an array of values

In this recipe we will learn how to use a standard data structure called an Array to store a list of names or values.

Getting ready

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.

How to do it...

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>

How it works...

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.

There's more

We should open up the uncompressed version of our MooTools and search for the phrase "include". We can quickly see how include() is an abstraction that enhances push().

主站蜘蛛池模板: 大埔区| 白山市| 含山县| 晋城| 元氏县| 沧州市| 绵竹市| 桃园市| 灌云县| 松阳县| 河池市| 林芝县| 永吉县| 晋城| 兴安盟| 成武县| 漯河市| 邹平县| 安平县| 囊谦县| 景洪市| 邹城市| 重庆市| 桂东县| 石阡县| 多伦县| 新郑市| 确山县| 景洪市| 河池市| 临颍县| 竹溪县| 秭归县| 太谷县| 富川| 淮南市| 平原县| 远安县| 孙吴县| 奇台县| 嘉黎县|