4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
5 <title>The source code</title>
6 <link href="../resources/prettify/prettify.css" type="text/css" rel="stylesheet" />
7 <script type="text/javascript" src="../resources/prettify/prettify.js"></script>
8 <style type="text/css">
9 .highlight { display: block; background-color: #ddd; }
11 <script type="text/javascript">
12 function highlight() {
13 document.getElementById(location.hash.replace(/#/, "")).className = "highlight";
17 <body onload="prettyPrint(); highlight();">
18 <pre class="prettyprint lang-js"><span id='Array'>/**
19 </span> * @class Array
21 * In JavaScript, the `Array` property of the global object is a constructor for
24 * An array is a JavaScript object. Note that you shouldn't use it as an
25 * associative array, use {@link Object} instead.
29 * The following example creates an array, msgArray, with a length of 0, then assigns values to
30 * msgArray[0] and msgArray[99], changing the length of the array to 100.
32 * var msgArray = new Array();
33 * msgArray[0] = "Hello";
34 * msgArray[99] = "world";
36 * if (msgArray.length == 100)
37 * print("The length is 100.");
39 * # Creating a Two-dimensional Array
41 * The following creates chess board as a two dimensional array of strings. The first move is made by
42 * copying the 'P' in 6,4 to 4,4. The position 4,4 is left blank.
45 * [ ['R','N','B','Q','K','B','N','R'],
46 * ['P','P','P','P','P','P','P','P'],
47 * [' ',' ',' ',' ',' ',' ',' ',' '],
48 * [' ',' ',' ',' ',' ',' ',' ',' '],
49 * [' ',' ',' ',' ',' ',' ',' ',' '],
50 * [' ',' ',' ',' ',' ',' ',' ',' '],
51 * ['p','p','p','p','p','p','p','p'],
52 * ['r','n','b','q','k','b','n','r']];
53 * print(board.join('\n') + '\n\n');
55 * // Move King's Pawn forward 2
56 * board[4][4] = board[6][4];
58 * print(board.join('\n'));
80 * # Accessing array elements
82 * Array elements are nothing less than object properties, so they are accessed as such.
84 * var myArray = new Array("Wind", "Rain", "Fire");
85 * myArray[0]; // "Wind"
86 * myArray[1]; // "Rain"
88 * myArray.length; // 3
90 * // Even if indices are properties, the following notation throws a syntax error
93 * // It should be noted that in JavaScript, object property names are strings. Consequently,
94 * myArray[0] === myArray["0"];
95 * myArray[1] === myArray["1"];
98 * // However, this should be considered carefully
99 * myArray[02]; // "Fire". The number 02 is converted as the "2" string
100 * myArray["02"]; // undefined. There is no property named "02"
102 * # Relationship between length and numerical properties
104 * An array's length property and numerical properties are connected. Here is some
105 * code explaining how this relationship works.
110 * console.log(a[0]); // 'a'
111 * console.log(a.length); // 1
114 * console.log(a[1]); // 32
115 * console.log(a.length); // 2
118 * console.log(a[13]); // 12345
119 * console.log(a.length); // 14
122 * console.log(a[13]); // undefined, when reducing the length elements after length+1 are removed
123 * console.log(a.length); // 10
125 * # Creating an array using the result of a match
127 * The result of a match between a regular expression and a string can create an array.
128 * This array has properties and elements that provide information about the match. An
129 * array is the return value of RegExp.exec, String.match, and String.replace. To help
130 * explain these properties and elements, look at the following example and then refer
131 * to the table below:
133 * // Match one d followed by one or more b's followed by one d
134 * // Remember matched b's and the following d
137 * var myRe = /d(b+)(d)/i;
138 * var myArray = myRe.exec("cdbBdbsbz");
140 * The properties and elements returned from this match are as follows:
143 * | Property/Element | Description | Example
144 * |:-----------------|:--------------------------------------------------------------------------------------|:-------------------
145 * | `input` | A read-only property that reflects the original string against which the | cdbBdbsbz
146 * | | regular expression was matched. |
147 * | `index` | A read-only property that is the zero-based index of the match in the string. | 1
148 * | `[0]` | A read-only element that specifies the last matched characters. | dbBd
149 * | `[1], ...[n]` | Read-only elements that specify the parenthesized substring matches, if included in | [1]: bB [2]: d
150 * | | the regular expression. The number of possible parenthesized substrings is unlimited. |
152 * <div class="notice">
153 * Documentation for this class comes from <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array">MDN</a>
154 * and is available under <a href="http://creativecommons.org/licenses/by-sa/2.0/">Creative Commons: Attribution-Sharealike license</a>.
159 <span id='Array-method-constructor'>/**
160 </span> * @method constructor
161 * Creates new Array object.
163 * @param {Number/Object...} items Either a number that specifies the length of array or any number of items
169 <span id='Array-property-length'>/**
170 </span> * @property {Number} length
171 * Reflects the number of elements in an array.
173 * The value of the `length` property is an integer with a positive sign and a value less than 2 to the 32
176 * You can set the `length` property to truncate an array at any time. When you extend an array by changing
177 * its `length` property, the number of actual elements does not increase; for example, if you set `length`
178 * to 3 when it is currently 2, the array still contains only 2 elements.
180 * In the following example the array numbers is iterated through by looking at the `length` property to see
181 * how many elements it has. Each value is then doubled.
183 * var numbers = [1,2,3,4,5];
184 * for (var i = 0; i < numbers.length; i++) {
187 * // numbers is now [2,4,6,8,10];
189 * The following example shortens the array `statesUS` to a length of 50 if the current `length` is greater
192 * if (statesUS.length > 50) {
197 // Mutator methods. These methods modify the array:
199 <span id='Array-method-pop'>/**
200 </span> * @method pop
201 * The pop method removes the last element from an array and returns that value to the caller.
203 * `pop` is intentionally generic; this method can be called or applied to objects resembling
204 * arrays. Objects which do not contain a length property reflecting the last in a series of
205 * consecutive, zero-based numerical properties may not behave in any meaningful manner.
207 * var myFish = ["angel", "clown", "mandarin", "surgeon"];
208 * var popped = myFish.pop();
209 * alert(popped); // Alerts 'surgeon'
211 * @return {Object} The last element in the array
214 <span id='Array-method-push'>/**
215 </span> * @method push
216 * Adds one or more elements to the end of an array and returns the new length of the array.
218 * `push` is intentionally generic. This method can be called or applied to objects resembling
219 * arrays. The push method relies on a length property to determine where to start inserting
220 * the given values. If the length property cannot be converted into a number, the index used
221 * is 0. This includes the possibility of length being nonexistent, in which case length will
224 * The only native, array-like objects are strings, although they are not suitable in
225 * applications of this method, as strings are immutable.
227 * ### Adding elements to an array
229 * The following code creates the sports array containing two elements, then appends two elements
230 * to it. After the code executes, sports contains 4 elements: "soccer", "baseball", "football"
231 * and "swimming".
233 * var sports = ["soccer", "baseball"];
234 * sports.push("football", "swimming");
236 * @param {Object...} elements The elements to add to the end of the array.
237 * @return {Number} The new length property of the object upon which the method was called.
240 <span id='Array-method-reverse'>/**
241 </span> * @method reverse
242 * Reverses the order of the elements of an array -- the first becomes the last, and the
243 * last becomes the first.
245 * The reverse method transposes the elements of the calling array object in place, mutating the
246 * array, and returning a reference to the array.
248 * The following example creates an array myArray, containing three elements, then reverses the array.
250 * var myArray = ["one", "two", "three"];
253 * This code changes myArray so that:
255 * - myArray[0] is "three"
256 * - myArray[1] is "two"
257 * - myArray[2] is "one"
259 * @return {Array} A reference to the array
262 <span id='Array-method-shift'>/**
263 </span> * @method shift
264 * Removes the first element from an array and returns that element.
266 * The `shift` method removes the element at the zeroeth index and shifts the values at consecutive
267 * indexes down, then returns the removed value.
269 * `shift` is intentionally generic; this method can be called or applied to objects resembling
270 * arrays. Objects which do not contain a `length` property reflecting the last in a series of
271 * consecutive, zero-based numerical properties may not behave in any meaningful manner.
273 * The following code displays the `myFish` array before and after removing its first element. It also
274 * displays the removed element:
276 * // assumes a println function is defined
277 * var myFish = ["angel", "clown", "mandarin", "surgeon"];
278 * println("myFish before: " + myFish);
279 * var shifted = myFish.shift();
280 * println("myFish after: " + myFish);
281 * println("Removed this element: " + shifted);
283 * This example displays the following:
285 * myFish before: angel,clown,mandarin,surgeon
286 * myFish after: clown,mandarin,surgeon
287 * Removed this element: angel
289 * @return {Object} The first element of the array prior to shifting.
292 <span id='Array-method-sort'>/**
293 </span> * @method sort
294 * Sorts the elements of an array.
296 * If `compareFunction` is not supplied, elements are sorted by converting them to strings and
297 * comparing strings in lexicographic ("dictionary" or "telephone book," not numerical) order. For
298 * example, "80" comes before "9" in lexicographic order, but in a numeric sort 9 comes before 80.
300 * If `compareFunction` is supplied, the array elements are sorted according to the return value of
301 * the compare function. If a and b are two elements being compared, then:
302 * If `compareFunction(a, b)` is less than 0, sort `a` to a lower index than `b`.
303 * If `compareFunction(a, b)` returns 0, leave `a` and `b` unchanged with respect to each other, but
304 * sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee
305 * this behaviour, and thus not all browsers respect this.
306 * If `compareFunction(a, b)` is greater than 0, sort `b` to a lower index than `a`.
307 * `compareFunction(a, b)` must always returns the same value when given a specific pair of elements a
308 * and b as its two arguments. If inconsistent results are returned then the sort order is undefined
310 * So, the compare function has the following form:
312 * function compare(a, b)
314 * if (a is less than b by some ordering criterion)
316 * if (a is greater than b by the ordering criterion)
318 * // a must be equal to b
322 * To compare numbers instead of strings, the compare function can simply subtract `b` from `a`:
324 * function compareNumbers(a, b)
329 * The sort() method can be conveniently used with closures:
331 * var numbers = [4, 2, 5, 1, 3];
332 * numbers.sort(function(a, b) {
337 * @param {Function} compareFunction Specifies a function that defines the sort order. If omitted, the
338 * array is sorted lexicographically (in dictionary order) according to the string conversion of each
340 * @return {Array} A reference to the array
343 <span id='Array-method-splice'>/**
344 </span> * @method splice
345 * Adds and/or removes elements from an array.
347 * If you specify a different number of elements to insert than the number you're removing, the array
348 * will have a different length at the end of the call.
350 * // assumes a print function is defined
351 * var myFish = ["angel", "clown", "mandarin", "surgeon"];
352 * print("myFish: " + myFish);
354 * var removed = myFish.splice(2, 0, "drum");
355 * print("After adding 1: " + myFish);
356 * print("removed is: " + removed);
358 * removed = myFish.splice(3, 1);
359 * print("After removing 1: " + myFish);
360 * print("removed is: " + removed);
362 * removed = myFish.splice(2, 1, "trumpet");
363 * print("After replacing 1: " + myFish);
364 * print("removed is: " + removed);
366 * removed = myFish.splice(0, 2, "parrot", "anemone", "blue");
367 * print("After replacing 2: " + myFish);
368 * print("removed is: " + removed);
370 * This script displays:
372 * myFish: angel,clown,mandarin,surgeon
373 * After adding 1: angel,clown,drum,mandarin,surgeon
375 * After removing 1: angel,clown,drum,surgeon
376 * removed is: mandarin
377 * After replacing 1: angel,clown,trumpet,surgeon
379 * After replacing 2: parrot,anemone,blue,trumpet,surgeon
380 * removed is: angel,clown
382 * @param {Number} index Index at which to start changing the array. If negative, will begin that
383 * many elements from the end.
384 * @param {Number} howMany An integer indicating the number of old array elements to remove. If
385 * `howMany` is 0, no elements are removed. In this case, you should specify at least one new element.
386 * If no `howMany` parameter is specified all elements after index are removed.
387 * @param {Object...} elements The elements to add to the array. If you don't specify any
388 * elements, `splice` simply removes elements from the array.
389 * @return {Array} An array containing the removed elements. If only one element is removed, an array
390 * of one element is returned..
393 <span id='Array-method-unshift'>/**
394 </span> * @method unshift
395 * Adds one or more elements to the front of an array and returns the new length of the array.
397 * The `unshift` method inserts the given values to the beginning of an array-like object.
399 * `unshift` is intentionally generic; this method can be called or applied to objects resembling
400 * arrays. Objects which do not contain a `length` property reflecting the last in a series of
401 * consecutive, zero-based numerical properties may not behave in any meaningful manner.
403 * The following code displays the myFish array before and after adding elements to it.
405 * // assumes a println function exists
406 * myFish = ["angel", "clown"];
407 * println("myFish before: " + myFish);
408 * unshifted = myFish.unshift("drum", "lion");
409 * println("myFish after: " + myFish);
410 * println("New length: " + unshifted);
412 * This example displays the following:
414 * myFish before: ["angel", "clown"]
415 * myFish after: ["drum", "lion", "angel", "clown"]
418 * @param {Object...} elements The elements to add to the front of the array.
419 * @return {Number} The array's new length.
422 // Accessor methods. These methods do not modify the array and return some representation of the array.
424 <span id='Array-method-concat'>/**
425 </span> * @method concat
426 * Returns a new array comprised of this array joined with other array(s) and/or value(s).
428 * `concat` creates a new array consisting of the elements in the `this` object on which it is called,
429 * followed in order by, for each argument, the elements of that argument (if the argument is an
430 * array) or the argument itself (if the argument is not an array).
432 * `concat` does not alter `this` or any of the arrays provided as arguments but instead returns a
433 * "one level deep" copy that contains copies of the same elements combined from the original arrays.
434 * Elements of the original arrays are copied into the new array as follows:
435 * Object references (and not the actual object): `concat` copies object references into the new
436 * array. Both the original and new array refer to the same object. That is, if a referenced object is
437 * modified, the changes are visible to both the new and original arrays.
438 * Strings and numbers (not {@link String} and {@link Number} objects): `concat` copies the values of
439 * strings and numbers into the new array.
441 * Any operation on the new array will have no effect on the original arrays, and vice versa.
443 * ### Concatenating two arrays
445 * The following code concatenates two arrays:
447 * var alpha = ["a", "b", "c"];
448 * var numeric = [1, 2, 3];
450 * // creates array ["a", "b", "c", 1, 2, 3]; alpha and numeric are unchanged
451 * var alphaNumeric = alpha.concat(numeric);
453 * ### Concatenating three arrays
455 * The following code concatenates three arrays:
457 * var num1 = [1, 2, 3];
458 * var num2 = [4, 5, 6];
459 * var num3 = [7, 8, 9];
461 * // creates array [1, 2, 3, 4, 5, 6, 7, 8, 9]; num1, num2, num3 are unchanged
462 * var nums = num1.concat(num2, num3);
464 * ### Concatenating values to an array
466 * The following code concatenates three values to an array:
468 * var alpha = ['a', 'b', 'c'];
470 * // creates array ["a", "b", "c", 1, 2, 3], leaving alpha unchanged
471 * var alphaNumeric = alpha.concat(1, [2, 3]);
473 * @param {Object...} values Arrays and/or values to concatenate to the resulting array.
474 * @return {Array} New array.
477 <span id='Array-method-join'>/**
478 </span> * @method join
479 * Joins all elements of an array into a string.
481 * The string conversions of all array elements are joined into one string.
483 * The following example creates an array, `a`, with three elements, then joins the array three times:
484 * using the default separator, then a comma and a space, and then a plus.
486 * var a = new Array("Wind","Rain","Fire");
487 * var myVar1 = a.join(); // assigns "Wind,Rain,Fire" to myVar1
488 * var myVar2 = a.join(", "); // assigns "Wind, Rain, Fire" to myVar2
489 * var myVar3 = a.join(" + "); // assigns "Wind + Rain + Fire" to myVar3
491 * @param {String} separator Specifies a string to separate each element of the array. The separator
492 * is converted to a string if necessary. If omitted, the array elements are separated with a comma.
493 * @return {String} A string of the array elements.
496 <span id='Array-method-slice'>/**
497 </span> * @method slice
498 * Extracts a section of an array and returns a new array.
500 * `slice` does not alter the original array, but returns a new "one level deep" copy that contains
501 * copies of the elements sliced from the original array. Elements of the original array are copied
502 * into the new array as follows:
503 * * For object references (and not the actual object), `slice` copies object references into the
504 * new array. Both the original and new array refer to the same object. If a referenced object
505 * changes, the changes are visible to both the new and original arrays.
506 * * For strings and numbers (not {@link String} and {@link Number} objects), `slice` copies strings
507 * and numbers into the new array. Changes to the string or number in one array does not affect the
510 * If a new element is added to either array, the other array is not affected.
514 * In the following example, `slice` creates a new array, `newCar`, from `myCar`. Both include a
515 * reference to the object `myHonda`. When the color of `myHonda` is changed to purple, both arrays
516 * reflect the change.
518 * // Using slice, create newCar from myCar.
519 * var myHonda = { color: "red", wheels: 4, engine: { cylinders: 4, size: 2.2 } };
520 * var myCar = [myHonda, 2, "cherry condition", "purchased 1997"];
521 * var newCar = myCar.slice(0, 2);
523 * // Print the values of myCar, newCar, and the color of myHonda
524 * // referenced from both arrays.
525 * print("myCar = " + myCar.toSource());
526 * print("newCar = " + newCar.toSource());
527 * print("myCar[0].color = " + myCar[0].color);
528 * print("newCar[0].color = " + newCar[0].color);
530 * // Change the color of myHonda.
531 * myHonda.color = "purple";
532 * print("The new color of my Honda is " + myHonda.color);
534 * // Print the color of myHonda referenced from both arrays.
535 * print("myCar[0].color = " + myCar[0].color);
536 * print("newCar[0].color = " + newCar[0].color);
538 * This script writes:
540 * myCar = [{color:"red", wheels:4, engine:{cylinders:4, size:2.2}}, 2, "cherry condition",
541 * "purchased 1997"]
542 * newCar = [{color:"red", wheels:4, engine:{cylinders:4, size:2.2}}, 2]
543 * myCar[0].color = red
544 * newCar[0].color = red
545 * The new color of my Honda is purple
546 * myCar[0].color = purple
547 * newCar[0].color = purple
549 * @param {Number} begin Zero-based index at which to begin extraction.
550 * As a negative index, `start` indicates an offset from the end of the sequence. `slice(-2)` extracts
551 * the second-to-last element and the last element in the sequence
552 * @param {Number} end Zero-based index at which to end extraction. `slice` extracts up to but not
554 * `slice(1,4)` extracts the second element through the fourth element (elements indexed 1, 2, and 3).
555 * As a negative index, end indicates an offset from the end of the sequence. `slice(2,-1)` extracts
556 * the third element through the second-to-last element in the sequence.
557 * If `end` is omitted, `slice` extracts to the end of the sequence.
558 * @return {Array} Array from the new start position up to (but not including) the specified end position.
561 <span id='Array-method-toString'>/**
562 </span> * @method toString
563 * Returns a string representing the array and its elements. Overrides the `Object.prototype.toString`
566 * The {@link Array} object overrides the `toString` method of {@link Object}. For Array objects, the
567 * `toString` method joins the array and returns one string containing each array element separated by
568 * commas. For example, the following code creates an array and uses `toString` to convert the array
571 * var monthNames = new Array("Jan","Feb","Mar","Apr");
572 * myVar = monthNames.toString(); // assigns "Jan,Feb,Mar,Apr" to myVar
574 * JavaScript calls the `toString` method automatically when an array is to be represented as a text
575 * value or when an array is referred to in a string concatenation.
577 * @return {String} The array as a string.