mozilla
검색 결과

    Array

    요약

    기본 객체

    배열을 사용할 수 있게 한다.

    생성

    Array 객체 생성자:

    new Array(arrayLength)
    new Array(element0,element1, ...,elementN)
    

    배열 기호를 이용한 생성:

    [element0,element1, ...,elementN]
    

    파라미터

    arrayLength
    배열의 길이를 지정합니다. 이 값은 length 속성을 통해 접근할 수 있습니다. 만약 지정한 값이 숫자가 아니라면, 첫번째 원소로 해당 값을 갖는 크기 1의 배열이 생성됩니다. 배열 길이의 최대값은 4,294,967,295입니다..
    element N
    배열 요소로 사용될 값의 목록입니다. 이 형식으로 배열을 생성할 경우, 배열은 지정한 값을 원소로 갖게 되며 배열의 크기는 지정한 원소의 갯수만큼이 됩니다.

    설명

    배열은 하나의 변수 이름에 속한 값들의 집합입니다. 이것은 연관 배열로 사용할 수 없으며, Object를 대신 사용해야 합니다.

    다음 예는 배열 기호를 이용해 배열 객체를 생성하는 것입니다. coffees 배열은 세 개의 원소를 갖으며 길이는 3입니다.

    coffees = ["French Roast", "Columbian", "Kona"];
    

    다음의 예도 세 개의 원소를 갖는 배열을 생성합니다. 배열의 인덱스는 0부터 시작합니다.

    myArray = new Array("Hello", myVar, 3.14159);
    

    배열 인덱스

    배열의 원소는 그 순서대로 접근할 수 있습니다. 다음과 같이 배열을 정의했다고 가정하면:

    myArray = new Array("Wind", "Rain", "Fire");
    

    각 원소는 아래와 같이 접근할 수 있습니다:

    • myArray[0]는 첫번째 원소
    • myArray[1]는 두번째 원소
    • myArray[2]는 세번째 원소

    하나의 파라미터

    Array 생성자의 파라미터로 숫자를 지정하여 배열의 길이를 지정할 수 있습니다. 다음 코드는 다섯 개의 원소를 갖는 배열을 생성합니다:

    billingMethod = new Array(5);
    

    생성자의 파라미터에 따라 Array 생성자는 달리 동작합니다.

    • 지정한 값이 숫자라면 생성자는 해당 숫자를 32 비트의 부호 없는 숫자로 변환하고 배열의 length 속성으로 지정합니다. 배열의 길이가 0이 아니더라도 배열을 생성한 초기에는 아무 값도 갖지 않습니다.
    • 지정한 값이 숫자가 아니라면 배열의 길이는 1이 되며, 지정한 값을 원소로 갖습니다.

    다음 코드는 길이가 25인 배열을 생성하고 처음 세 원소에 값을 할당합니다.

    musicTypes = new Array(25);
    musicTypes[0] = "R&B";
    musicTypes[1] = "Blues";
    musicTypes[2] = "Jazz";
    

    배열 길이 증가

    현재 길이보다 큰 값을 배열 원소로 지정할 경우 배열 길이는 증가합니다. 다음 코드는 길이 0의 배열을 생성하고 99번 원소를 할당함으로써 배열 길이를 100으로 변경합니다.

    colors = new Array();
    colors[99] = "midnightblue";
    

    일치된 결과를 이용한 배열 생성

    The result of a match between a regular expression and a string can create an array. This array has properties and elements that provide information about the match. An array is the return value of RegExp.exec, String.match, and String.replace. To help explain these properties and elements, look at the following example and then refer to the table below:

    // Match one d followed by one or more b's followed by one d
    // Remember matched b's and the following d
    // Ignore case
    
    myRe = /d(b+)(d)/i;
    myArray = myRe.exec("cdbBdbsbz");
    

    The properties and elements returned from this match are as follows:

    Property/Element Description Example
    input A read-only property that reflects the original string against which the regular expression was matched. cdbBdbsbz
    index A read-only property that is the zero-based index of the match in the string. 1
    [0] A read-only element that specifies the last matched characters. dbBd
    [1], ...[n] Read-only elements that specify the parenthesized substring matches, if included in the regular expression. The number of possible parenthesized substrings is unlimited. [1]: bB
    [2]: d

    Behavior in older versions

    JavaScript 1.2

    When a single parameter was given to the Array constructor in an interpreter executing code as JavaScript 1.2, a single-element array was returned. For example, new Array(5) created a one-element array with the first element being 5.

    JavaScript 1.0

    Indexing an array by its ordinal number was required; for example:

    myArray[0].
    

    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

    need a better name...

    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).
    indexOf
    Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found.
    join
    Joins all elements of an array into a string.
    lastIndexOf
    Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found.
    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.

    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.

    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:

    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 a two-dimensional array and assigns the results to myVar.

    var myVar = "Multidimensional array test; ";
    a = new Array(4);
    for (var i = 0; i < 4; i++) {
       a[i] = new Array(4);
       for (var j = 0; j < 4; j++) {
          a[i][j] = "[" + i + "," + j + "]";
       }
    }
    for (var i = 0; i < 4; i++) {
       str = "Row " + i + ":";
       for (var j = 0; j < 4; j++) {
          str += a[i][j];
       }
       myVar += str + "; ";
    }
    

    The following string is assigned to myVar (line breaks are used here for readability):

    Multidimensional array test;
    Row 0: [0,0][0,1][0,2][0,3];
    Row 1: [1,0][1,1][1,2][1,3];
    Row 2: [2,0][2,1][2,2][2,3];
    Row 3: [3,0][3,1][3,2][3,3];
    

    문서 태그 및 공헌자

    Contributors to this page: 행복한고니, Aeuiop, teoli
    최종 변경: teoli,