Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

이 글은 편집 검토가 필요합니다. 도울을 줄 수 있는 방법을 살펴보세요.

현재 번역은 완벽하지 않습니다. 한국어로 문서 번역에 동참해주세요.

요약

JavaScript Array 객체는 리스트와 비슷한 고수준의 객체인 배열을 생성하는 데 사용되는 전역 객체입니다.

배열 만들기

var fruits = ["사과", "바나나"];

console.log(fruits.length);
// 2

인덱스로 배열의 항목에 접근하기

var first = fruits[0];
// 사과

var last = fruits[fruits.length - 1];
// 바나나

배열의 항목 각각에 대해 반복하기

fruits.forEach(function (item, index, array) {
  console.log(item, index);
});
// 사과 0
// 바나나 1

배열 뒤에 항목 추가하기

var newLength = fruits.push("오렌지");
// ["사과", "바나나", "오렌지"]

배열 뒤에서 항목 제거하기

var last = fruits.pop(); // 뒤에서 오렌지를 제거
// ["사과", "바나나"];

배열 앞에서 항목 제거하기

var first = fruits.shift(); // 앞에서 사과를 제거
// ["바나나"];

배열 앞에 항목 추가하기

var newLength = fruits.unshift("딸기") // 앞에 추가
// ["딸기", "바나나"];

배열 안 항목의 인덱스 찾기

fruits.push("망고");
// ["딸기", "바나나", "망고"]

var pos = fruits.indexOf("바나나");
// 1

인덱스 위치에 있는 항목 제거하기

var removedItem = fruits.splice(pos, 1); // 항목을 제거하는 방법
// ["딸기", "망고"]

배열 복사하기

var shallowCopy = fruits.slice(); // 사본을 만드는 방법
// ["딸기", "망고"]

구문

[element0, element1, ..., elementN]
new Array(element0, element1[, ...[, elementN]])
new Array(arrayLength)
elementN
JavaScript 배열이 주어진 요소들로 초기화됩니다. 단, 하나의 인수만 Array 생성자에 전달되었고 그것이 수일 때는 예외입니다. (아래를 보십시오.) 이 특별한 경우는 괄호 구문으로 만들어진 배열 값이 아닌 Array 생성자에 의해 만들어진 JavaScript 배열에만 적용됨에 유의하십시오.
arrayLength
만약 Array 생성자에 전달된 인수가 0과 232-1 사이의 정수(끝값 포함) 하나뿐이라면, 생성자는 그 정수만큼의 길이를 가진 새 JavaScript 배열을 반환합니다. 만약 인수가 이에 포함되지 않는 수라면, RangeError 예외가 발생합니다.

설명

배열은 프로토타입으로 탐색과 변형 작업을 수행하는 메서드를 갖는, 리스트와 비슷한 객체입니다. JavaScript 배열의 길이와 요소들의 타입은 고정되어 있지 않습니다. 배열의 길이가 언제든지 늘어나거나 줄어들 수 있기 때문에, JavaScript arrays are not guaranteed to be dense. 보통 이 성질은 편리합니다. 하지만 이 기능이 당신의 목적에 맞지 않는다면, 타입을 가진 배열을 사용하는 것을 고려해야 할 지도 모릅니다.

몇몇 사람들은 배열을 연관 배열로 사용해서는 안 된다고 생각합니다. 그 대신에 객체를 사용할 수 있지만, 그것은 그 나름대로 주의가 필요합니다. Lightweight JavaScript dictionaries with arbitrary keys 포스트에 그 예시가 있습니다.

배열 요소에 접근하기

JavaScript 배열의 인덱스는 0부터 시작합니다. 즉, 배열의 첫 번째 요소의 인덱스는 0이고, 마지막 요소의 인덱스는 배열의 length 속성에서 1을 뺀 것과 같습니다.

var arr = ['첫 번재 요소입니다', '두 번째 요소입니다'];
console.log(arr[0]);              // '첫 번재 요소입니다'를 기록
console.log(arr[1]);              // '두 번재 요소입니다'를 기록
console.log(arr[arr.length - 1]); // '두 번재 요소입니다'를 기록

toString이 속성인 것과 마찬가지로 배열의 요소도 속성입니다. 하지만 다음과 같이 배열의 요소에 접근하려 하면, 속성 이름이 잘못되었기 때문에 구문 오류가 발생합니다.

console.log(arr.0); // 구문 오류

There is nothing special about JavaScript arrays and the properties that cause this. 숫자로 시작하는 JavaScript 속성은 점 표현으로 참조할 수 없고 대괄호 표현을 사용해서만 참조할 수 있습니다. 만약 '3d'라는 속성을 가진 객체가 있다면, 그 속성은 대괄호 표현으로만 참조할 수 있습니다. 예를 들면,

var years = [1950, 1960, 1970, 1980, 1990, 2000, 2010];
console.log(years.0);   // 구문 오류
console.log(years[0]);  // 정상 작동
renderer.3d.setTexture(model, 'character.png');     // 구문 오류
renderer['3d'].setTexture(model, 'character.png');  // 정상 작동

3d 예시에서 '3d'가 따옴표로 둘러싸여야 함에 유의하십시오. JavaScript 배열 인덱스도 따옴표로 둘러쌀 수 있지만(years[2] 대신에 years['2']처럼) 꼭 필요하지는 않습니다. years[2]의 2는 JavaScript 엔진이 toString 변환을 사용해 강제로 문자열로 변환합니다. '2''02'years 객체의 서로 다른 두 개의 칸을 가리켜서 다음 예시가 true일 수 있기 때문입니다.

console.log(years['2'] != years['02']);

마찬가지로, 객체가 예약어를 속성으로 갖게 되었을 때(!) 그 속성은 대괄호 표현의 문자열 값으로만 접근할 수 있습니다(하지만 Firefox 40.0a2까지는 점 표현으로 접근할 수 있습니다).

var promise = {
  'var'  : 'text',
  'array': [1, 2, 3, 4]
};

console.log(promise['array']);

length 와 숫자형 속성의 관계

자바스크립트 배열의 length 속성과 숫자형 속성은 연결되어 있습니다. 몇몇 배열 내장 메소드들(예: join, slice, indexOf, 등등.)은 호출되었을 때 배열의 length 속성의 값을 참조합니다. 다른 메소드들(예: push, splice, 등등.) 또한 배열의 length 속성을 업데이트을 유발합니다.

var fruits = [];
fruits.push('banana', 'apple', 'peach');

console.log(fruits.length); // 3

자바스크립트 배열의 속성을 설정할 때 그 속성이 유효한 배열 인덱스이고 그 인덱스가 현재 배열의 경계(bounds)를 넘어간다면, 엔진은 배열의 length 속성을 그에 맞춰 업데이트 합니다:

fruits[5] = 'mango';
console.log(fruits[5]); // 'mango'
console.log(Object.keys(fruits));  // ['0', '1', '2', '5']
console.log(fruits.length); // 6

length 증가.

fruits.length = 10;
console.log(Object.keys(fruits)); // ['0', '1', '2', '5']
console.log(fruits.length); // 10

하지만, length 속성을 감소시키면 요소(element)를 지웁니다.

fruits.length = 2;
console.log(Object.keys(fruits)); // ['0', '1']
console.log(fruits.length); // 2

이것은 Array.length 페이지에 더 설명되어있습니다.

매치 결과를 이용한 배열 생성

정규표현식과 문자열 사이의 매치 결과로 자바스크립트 배열을 만들 수 있습니다. 이 배열은 매치에 대한 정보를 제공하는 속성들과 요소들을 가집니다. 이러한 배열은 RegExp.exec, String.matchString.replace로부터 반환됩니다. 이 속성들과 요소들에 대한 설명을 돕기위해, 다음 예제를 보고 아래 테이블을 참조해주세요.

// Match one d followed by one or more b's followed by one d
// Remember matched b's and the following d
// Ignore case

var myRe = /d(b+)(d)/i;
var myArray = myRe.exec('cdbBdbsbz');

매치로부터 반환되는 속성들과 요소들은 다음과 같습니다:

속성/요소 설명
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

속성

For properties available on Array instances, see Properties of Array instances.
Array.length
The Array constructor's length property whose value is 1.
Array.prototype
Allows the addition of properties to all array objects.

메소드

For methods available on Array instances, see Methods of Array instances.
Array.from()
Creates a new Array instance from an array-like or iterable object.
Array.isArray()
Returns true if a variable is an array, if not false.
Array.observe()
Asynchronously observes changes to Arrays, similar to Object.observe() for objects. It provides a stream of changes in order of occurrence.
Array.of()
Creates a new Array instance with a variable number of arguments, regardless of number or type of the arguments.

배열 인스턴스

모든 배열 인스턴스는 Array.prototype로부터 상속을 받습니다. 배열 생성자의 프로토타입 객체는 모든 배열 인스턴스에 영향을 주도록 수정될 수 있습니다.

속성

Array.prototype.constructor
Specifies the function that creates an object's prototype.
Array.prototype.length
Reflects the number of elements in an array.
Array.prototype[@@unscopables]
A symbol containing property names to exclude from a with binding scope.

 

메소드

Mutator methods

These methods modify the array:

Array.prototype.copyWithin()
Copies a sequence of array elements within the array.
Array.prototype.fill()
Fills all the elements of an array from a start index to an end index with a static value.
Array.prototype.pop()
Removes the last element from an array and returns that element.
Array.prototype.push()
Adds one or more elements to the end of an array and returns the new length of the array.
Array.prototype.reverse()
Reverses the order of the elements of an array in place — the first becomes the last, and the last becomes the first.
Array.prototype.shift()
Removes the first element from an array and returns that element.
Array.prototype.sort()
Sorts the elements of an array in place and returns the array.
Array.prototype.splice()
Adds and/or removes elements from an array.
Array.prototype.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.

Array.prototype.concat()
Returns a new array comprised of this array joined with other array(s) and/or value(s).
Array.prototype.includes()
Determines whether an array contains a certain element, returning true or false as appropriate.
Array.prototype.join()
Joins all elements of an array into a string.
Array.prototype.slice()
Extracts a section of an array and returns a new array.
Array.prototype.toSource()
Returns an array literal representing the specified array; you can use this value to create a new array. Overrides the Object.prototype.toSource() method.
Array.prototype.toString()
Returns a string representing the array and its elements. Overrides the Object.prototype.toString() method.
Array.prototype.toLocaleString()
Returns a localized string representing the array and its elements. Overrides the Object.prototype.toLocaleString() method.
Array.prototype.indexOf()
Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found.
Array.prototype.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. While the specific behavior of these methods in such cases is well-defined, you should not rely upon it so as not to confuse others who might read your code. If you must mutate the array, copy into a new array instead.

Array.prototype.forEach()
Calls a function for each element in the array.
Array.prototype.entries()
Returns a new Array Iterator object that contains the key/value pairs for each index in the array.
Array.prototype.every()
Returns true if every element in this array satisfies the provided testing function.
Array.prototype.some()
Returns true if at least one element in this array satisfies the provided testing function.
Array.prototype.filter()
Creates a new array with all of the elements of this array for which the provided filtering function returns true.
Array.prototype.find()
Returns the found value in the array, if an element in the array satisfies the provided testing function or undefined if not found.
Array.prototype.findIndex()
Returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found.
Array.prototype.keys()
Returns a new Array Iterator that contains the keys for each index in the array.
Array.prototype.map()
Creates a new array with the results of calling a provided function on every element in this array.
Array.prototype.reduce()
Apply a function against an accumulator and each value of the array (from left-to-right) as to reduce it to a single value.
Array.prototype.reduceRight()
Apply a function against an accumulator and each value of the array (from right-to-left) as to reduce it to a single value.
Array.prototype.values()
Returns a new Array Iterator object that contains the values for each index in the array.
Array.prototype[@@iterator]()
Returns a new Array Iterator object that contains the values for each index in the array.

Array generic methods

Array generics are non-standard, deprecated and will get removed near future. Note that you can not rely on them cross-browser. However, there is a shim available on GitHub.

Sometimes you would like to apply array methods to strings or other array-like objects (such as function arguments). By doing this, you treat a string as an array of characters (or otherwise treat a non-array as an array). For example, in order to check that every character in the variable str is a letter, you would write:

function isLetter(character) {
  return character >= 'a' && character <= 'z';
}

if (Array.prototype.every.call(str, isLetter)) {
  console.log("The string '" + str + "' contains only letters!");
}

This notation is rather wasteful and JavaScript 1.6 introduced a generic shorthand:

if (Array.every(str, isLetter)) {
  console.log("The string '" + str + "' contains only letters!");
}

Generics are also available on String.

These are not part of ECMAScript standards (though the ES6 Array.from() can be used to achieve this). The following is a shim to allow its use in all browsers:

// Assumes Array extras already present (one may use polyfills for these as well)
(function() {
  'use strict';

  var i,
    // We could also build the array of methods with the following, but the
    //   getOwnPropertyNames() method is non-shimable:
    // Object.getOwnPropertyNames(Array).filter(function(methodName) {
    //   return typeof Array[methodName] === 'function'
    // });
    methods = [
      'join', 'reverse', 'sort', 'push', 'pop', 'shift', 'unshift',
      'splice', 'concat', 'slice', 'indexOf', 'lastIndexOf',
      'forEach', 'map', 'reduce', 'reduceRight', 'filter',
      'some', 'every', 'find', 'findIndex', 'entries', 'keys',
      'values', 'copyWithin', 'includes'
    ],
    methodCount = methods.length,
    assignArrayGeneric = function(methodName) {
      if (!Array[methodName]) {
        var method = Array.prototype[methodName];
        if (typeof method === 'function') {
          Array[methodName] = function() {
            return method.call.apply(method, arguments);
          };
        }
      }
    };

  for (i = 0; i < methodCount; i++) {
    assignArrayGeneric(methods[i]);
  }
}());

예제

배열 생성

아래 예제는 길이 0의 배열 msgArray 을 생성하고, msgArray[0] 와 msgArray[99] 에 값을 할당하여, 배열의 길이를 100으로 변경합니다.

var msgArray = [];
msgArray[0] = 'Hello';
msgArray[99] = 'world';

if (msgArray.length === 100) {
  console.log('The length is 100.');
}

2차원 배열 생성

아래는 2차원 문자열 배열로 체스보드를 생성합니다. 첫번째 이동은 (6,4)의 'p'를 (4,4)로 복사하여 이루어집니다. 이전 위치 (6,4)는 빈공간으로 만듭니다.

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'] ];

console.log(board.join('\n') + '\n\n');

// Move King's Pawn forward 2
board[4][4] = board[6][4];
board[6][4] = ' ';
console.log(board.join('\n'));

결과는 다음과 같습니다:

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

명세

Specification Status Comment
ECMAScript 1st Edition (ECMA-262) Standard Initial definition.
ECMAScript 5.1 (ECMA-262)
The definition of 'Array' in that specification.
Standard New methods added: Array.isArray, indexOf, lastIndexOf, every, some, forEach, map, filter, reduce, reduceRight
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'Array' in that specification.
Standard New methods added: Array.from, Array.of, find, findIndex, fill, copyWithin

브라우저 호환성

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) (Yes) (Yes) (Yes) (Yes)
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (Yes) (Yes) (Yes) (Yes) (Yes) (Yes)

참조

문서 태그 및 공헌자

 이 페이지의 공헌자: joeunha, maytree, VBChunguk, JaegangLee, teoli, taggon, Aeuiop
 최종 변경: joeunha,