Core JavaScript 1.5 Reference:Global Objects:Array
Материал из MDC.
Содержание |
[править] Аннотация (Summary)
Встроенный объект Array
Объект Array используется для создания массивов, т. е. упорядоченных наборов элементов.
Массив JavaScript может включать любой тип данных, в т.ч. различные типы данных в одном массиве. Каждому элементу в массиве назначен индекс (его номер в массиве). По умолчанию индекс - отсчитываемое от нуля целое число (первый элемент имеет индекс 0).
Доступ к элементу массива производится по индексу.
В приведенной ниже таблице сведены все методы и свойства объекта Array.
Методы и свойства объекта Array.
| Методы / Свойства | Описание |
| Методы | |
| concat() | Соединяет элементы существующего массива. |
| join() | Соединяет все элементы массива в одну строку. |
| рор() | Удаляет последний элемент массива. |
| push() | Добавляет элементы в конец массива. |
| reverse() | Изменяет порядок следования элементов в массиве. |
| shift() | Удаляет элементы в начале массива. |
| slice() | Возвращает часть массива. |
| sort() | Сортирует элементы в массиве. |
| splice() | Вставляет и удаляет элементы из массива. |
| toSource() | Преобразует элементы в строку с квадратными скобками. |
| toString() | Преобразует элементы массива в строку. |
| unshift() | Добавляет элементы в начало массива. |
| Свойства | |
| valueOf() | Возвращает массив элементов, отделенных запятыми. |
| index | Возвращает индекс совпадения в строке для массива, созданного в соответствие с регулярным выражением. |
| input | Для массива, созданного в соответствие с регулярным выражением свойство возвращает исходную строку. |
| length | Количество элементов в массиве. |
| prototype | Позволяет добавлять свойства к экземплярам объекта Array. |
[править] Создание массивов (Created by)
Для создания массивов используются следующие конструкторы массивов (The Array object constructor):
new Array() new Array(arrayLength) new Array(element0, element1, ..., elementN)
- arrayLength - любое числовое выражение, задающее количество элементов в массиве (длину массива). Максимальная допустимая длина массива - 4,294,967,295;
- element0, element1, ..., elementN - список элементов множества, состоящий из любых выражений.
Первый конструктор создает пустой массив, второй - массив из arrayLength элементов, третий создает массив из N+1 элементов и присваивает им соответствующие значения. Если arrayLength не является числом без знака, то создается массив с единственным элементом, имеющим это значение.
Кроме того, массив может быть создан с помощью инициализатора массива (создание массива в литеральной нотации):
[element0, element1, ..., elementN]
Можно неявно увеличить размер массива, присвоив значение элементу с несуществующим индексом, например:
var colors = new Array(); // пустой массив colors[99] = "midnightblue"; // размер массива стал равен 100
[править] Создание массива по результату сопоставления строки с регулярным выражением
Функции сопоставления строки с регулярным выражением (RegExp.exec, String.match и String.replace) в качестве результата возвращают массив (результирующий массив). Этот массив имеет элементы и свойства, которые содержат информацию о результате сопоставления.Такой массив, помимо стандартных свойств, обладает дополнительными свойствами index и input.
Рассмотрим пример:
//Совпадает один символ d, с последующим одним или более b, с последующим одним d
// Сохранить совпавшие подстроки (b+)и(d)в элементах результирующего массива
// Игнорировать регистр
var myRe = /d(b+)(d)/i;
var myArray = myRe.exec("cdbBdbsbz");
В таблице показан результат работы скрипта:
| Свойство/Элемент | Описание | Значение |
input
| Значением свойства является последняя исходная строка, к которой применялось сопоставление с образцом. | cdbBdbsbz |
index
| Значением свойства является индекс совпадений в строке с базой 0. | 1 |
[0]
| Последние совпавшие символы. | dbBd |
[1], ...[n]
| Совпадения подстрок в скобках, если имеются. Количество подстрок в скобках не ограничивается.. | [1]: bB [2]: d |
[править] Properties
- constructor
- Specifies the function that creates an object's prototype.
- index
- For an array created by a regular expression match, the zero-based index of the match in the string.
- input
- For an array created by a regular expression match, reflects the original string against which the regular expression was matched.
- length
- Reflects the number of elements in an array.
- prototype
- Allows the addition of properties to all objects.
[править] Methods
[править] Mutator methods
These methods modify the array:
- pop
- Removes the last element from an array and returns that element.
- push
- Adds one or more elements to the end of an array and returns the new length of the array.
- reverse
- Reverses the order of the elements of an array -- the first becomes the last, and the last becomes the first.
- shift
- Removes the first element from an array and returns that element.
- sort
- Sorts the elements of an array.
- splice
- Adds and/or removes elements from an array.
- unshift
- Adds one or more elements to the front of an array and returns the new length of the array.
[править] Accessor methods
These methods do not modify the array and return some representation of the array.
- concat
- Returns a new array comprised of this array joined with other array(s) and/or value(s).
- join
- Joins all elements of an array into a string.
- slice
- Extracts a section of an array and returns a new array.
- toSource
- Returns an array literal representing the specified array; you can use this value to create a new array. Overrides the Object.toSource method.
- toString
- Returns a string representing the array and its elements. Overrides the Object.toString method.
- valueOf
- Returns the primitive value of the array. Overrides the Object.valueOf method.
- indexOf
- Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found.
- lastIndexOf
- Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found.
[править] Iteration methods
Several methods take as arguments functions to be called back while processing the array. When these methods are called, the length of the array is sampled, and any element added beyond this length from within the callback is not visited. Other changes to the array (setting the value of or deleting an element) may affect the results of the operation if the method visits the changed element afterwards. The specific behaviour of these methods in such cases is not always well-defined, and should not be relied upon.
- filter
- Creates a new array with all of the elements of this array for which the provided filtering function returns true.
- forEach
- Calls a function for each element in the array.
- every
- Returns true if every element in this array satisfies the provided testing function.
- map
- Creates a new array with the results of calling a provided function on every element in this array.
- some
- Returns true if at least one element in this array satisfies the provided testing function.
- reduce
- Apply a function simultaneously against two values of the array (from left-to-right) as to reduce it to a single value.
- reduceRight
- Apply a function simultaneously against two values of the array (from right-to-left) as to reduce it to a single value.
[править] Generic methods
Many methods on the JavaScript Array object are designed to be generally applied to all objects which "look like" Arrays. That is, they can be used on any object which has a length property, and which can usefully be accessed using numeric property names (as with array[5] indexing).
TODO: give examples with Array.prototype.forEach.call, and adding the method to an object like JavaArray or String.
Some methods, such as join, only read the length and numeric properties of the object they are called on. Others, like reverse, require that the object's numeric properties and length be mutable; these methods can therefore not be called on objects like String, which does not permit its length property or synthesized numeric properties to be set.
The methods that work on any Array-like object and do not need to alter length or numeric properties are:
- concat
- every (JS 1.6+)
- filter (JS 1.6+)
- forEach (JS 1.6+)
- indexOf (JS 1.6+)
- join
- lastIndexOf (JS 1.6+)
- map (JS 1.6+)
- slice
- some (JS 1.6+)
- toSource
- toString
- valueOf
The methods that alter the length or numeric properties of the object they are called on are:
This example shows how to use map on a string object to get an array of bytes in the ASCII encoding representing the character values:
var a = Array.prototype.map.call("Hello World",
function(x) { return x.charCodeAt(0); })
// a now equals [72,101,108,108,111,32,87,111,114,108,100]
[править] Examples
[править] Example: Creating an Array
The following example creates an array, msgArray, with a length of 0, then assigns values to msgArray[0] and msgArray[99], changing the length of the array to 100.
var msgArray = new Array(); msgArray[0] = "Hello"; msgArray[99] = "world"; // The following statement is true, // because defined msgArray[99] element. if (msgArray.length == 100) myVar = "The length is 100.";
[править] Example: Creating a Two-dimensional Array
The following creates chess board as a two dimensional array of strings. The first move is made by copying the 'P' in 1,4 to 3,4. The position 1,4 is left blank.
var board =
[ ['R','N','B','Q','K','B','N','R'],
['P','P','P','P','P','P','P','P'],
[' ',' ',' ',' ',' ',' ',' ',' '],
[' ',' ',' ',' ',' ',' ',' ',' '],
[' ',' ',' ',' ',' ',' ',' ',' '],
[' ',' ',' ',' ',' ',' ',' ',' '],
['p','p','p','p','p','p','p','p'],
['r','n','b','q','k','b','n','r']];
print(board.join('\n'));
print('\n\n\n');
// Move King's Pawn forward 2
board[3][4] = board[1][4];
board[1][4] = ' ';
print(board.join('\n'));
Here is the output:
R,N,B,Q,K,B,N,R P,P,P,P,P,P,P,P , , , , , , , , , , , , , , , , , , , , , , , , , , , , p,p,p,p,p,p,p,p r,n,b,q,k,b,n,r R,N,B,Q,K,B,N,R P,P,P,P, ,P,P,P , , , , , , , , , , ,P, , , , , , , , , , , , , , , , , p,p,p,p,p,p,p,p r,n,b,q,k,b,n,r
--George Begun 05:18, 27 октября 2007 (PDT)