From da78a9e329e272dedb2400b79a3bdeebff387d47 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:42:17 -0500 Subject: initial commit --- .../global_objects/array/@@iterator/index.html | 84 +++ .../global_objects/array/@@species/index.html | 75 +++ .../global_objects/array/@@unscopables/index.html | 72 +++ .../global_objects/array/array/index.html | 86 ++++ .../global_objects/array/concat/index.html | 138 +++++ .../global_objects/array/copywithin/index.html | 183 +++++++ .../global_objects/array/entries/index.html | 89 ++++ .../global_objects/array/every/index.html | 191 +++++++ .../reference/global_objects/array/fill/index.html | 146 ++++++ .../global_objects/array/filter/index.html | 231 +++++++++ .../reference/global_objects/array/find/index.html | 226 ++++++++ .../global_objects/array/findindex/index.html | 146 ++++++ .../reference/global_objects/array/flat/index.html | 160 ++++++ .../global_objects/array/flatmap/index.html | 148 ++++++ .../global_objects/array/foreach/index.html | 264 ++++++++++ .../reference/global_objects/array/from/index.html | 244 +++++++++ .../global_objects/array/includes/index.html | 173 +++++++ .../reference/global_objects/array/index.html | 493 ++++++++++++++++++ .../global_objects/array/indexof/index.html | 196 +++++++ .../global_objects/array/isarray/index.html | 131 +++++ .../reference/global_objects/array/join/index.html | 91 ++++ .../reference/global_objects/array/keys/index.html | 69 +++ .../global_objects/array/lastindexof/index.html | 103 ++++ .../global_objects/array/length/index.html | 135 +++++ .../reference/global_objects/array/map/index.html | 293 +++++++++++ .../global_objects/array/observe/index.html | 87 ++++ .../reference/global_objects/array/of/index.html | 104 ++++ .../reference/global_objects/array/pop/index.html | 91 ++++ .../reference/global_objects/array/push/index.html | 113 ++++ .../global_objects/array/reduce/index.html | 573 +++++++++++++++++++++ .../global_objects/array/reduceright/index.html | 283 ++++++++++ .../global_objects/array/reverse/index.html | 87 ++++ .../global_objects/array/shift/index.html | 102 ++++ .../global_objects/array/slice/index.html | 155 ++++++ .../reference/global_objects/array/some/index.html | 202 ++++++++ .../reference/global_objects/array/sort/index.html | 245 +++++++++ .../global_objects/array/splice/index.html | 153 ++++++ .../global_objects/array/tolocalestring/index.html | 195 +++++++ .../global_objects/array/tosource/index.html | 71 +++ .../global_objects/array/tostring/index.html | 80 +++ .../global_objects/array/unshift/index.html | 91 ++++ .../global_objects/array/values/index.html | 87 ++++ 42 files changed, 6886 insertions(+) create mode 100644 files/ko/web/javascript/reference/global_objects/array/@@iterator/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/@@species/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/@@unscopables/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/array/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/concat/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/copywithin/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/entries/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/every/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/fill/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/filter/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/find/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/findindex/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/flat/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/flatmap/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/foreach/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/from/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/includes/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/indexof/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/isarray/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/join/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/keys/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/lastindexof/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/length/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/map/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/observe/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/of/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/pop/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/push/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/reduce/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/reduceright/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/reverse/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/shift/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/slice/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/some/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/sort/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/splice/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/tolocalestring/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/tosource/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/tostring/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/unshift/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/values/index.html (limited to 'files/ko/web/javascript/reference/global_objects/array') diff --git a/files/ko/web/javascript/reference/global_objects/array/@@iterator/index.html b/files/ko/web/javascript/reference/global_objects/array/@@iterator/index.html new file mode 100644 index 0000000000..89e08aa41e --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/@@iterator/index.html @@ -0,0 +1,84 @@ +--- +title: 'Array.prototype[@@iterator]()' +slug: Web/JavaScript/Reference/Global_Objects/Array/@@iterator +tags: + - Array + - ECMAScript 2015 + - Iterator + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/@@iterator +--- +
{{JSRef}}
+ +

 @@iterator 속성의 초기 값은 {{jsxref("Array.prototype.values()", "values()")}} 속성의 초기 값과 같은 함수 객체입니다.

+ +

구문

+ +
arr[Symbol.iterator]()
+ +

반환 값

+ +

{{jsxref("Array.prototype.values()", "values()")}} 반복기가 반환하는 초기 값. arr[Symbol.iterator]의 기본값은 {{jsxref("Array.prototype.values()", "values()")}} 입니다.

+ +

예제

+ +

for…of 반복문을 이용한 순회

+ +
var arr = ['w', 'y', 'k', 'o', 'p'];
+var eArr = arr[Symbol.iterator]();
+// your browser must support for..of loop
+// and let-scoped variables in for loops
+// const and var could also be used
+for (let letter of eArr) {
+  console.log(letter);
+}
+ +

다른 방법

+ +
var arr = ['w', 'y', 'k', 'o', 'p'];
+var eArr = arr[Symbol.iterator]();
+console.log(eArr.next().value); // w
+console.log(eArr.next().value); // y
+console.log(eArr.next().value); // k
+console.log(eArr.next().value); // o
+console.log(eArr.next().value); // p
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
명세상태비고
{{SpecName('ES6', '#sec-array.prototype-@@iterator', 'Array.prototype[@@iterator]()')}}{{Spec2('ES2015')}}초기 정의.
{{SpecName('ESDraft', '#sec-array.prototype-@@iterator', 'Array.prototype[@@iterator]()')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +
{{Compat("javascript.builtins.Array.@@iterator")}}
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/@@species/index.html b/files/ko/web/javascript/reference/global_objects/array/@@species/index.html new file mode 100644 index 0000000000..7b1bda0ca6 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/@@species/index.html @@ -0,0 +1,75 @@ +--- +title: 'get Array[@@species]' +slug: Web/JavaScript/Reference/Global_Objects/Array/@@species +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/@@species +--- +
{{JSRef}}
+ +

Array[@@species] 접근자 속성은 Array 생성자를 반환합니다.

+ +

구문

+ +
Array[Symbol.species]
+
+ +

반환 값

+ +

{{jsxref("Array")}} 생성자.

+ +

설명

+ +

species 접근자 속성은 Array 객체의 기본 생성자를 반환합니다. 서브클래스 생성자는 생성자 할당을 변경하기 위해 이 속성을 재정의할 수 있습니다.

+ +

예제

+ +

species 속성은 Array 객체의 Array 생성자를 반환합니다.

+ +
Array[Symbol.species]; // function Array()
+ +

파생 콜렉션 개체(예시: 사용자 설정 배열인 MyArray)에서, MyArrayspeciesMyArray 생성자입니다. 그러나 이 속성을 재정의하면 파생 클래스 메서드에서 상위 Array 객체를 반환할 수 있습니다.

+ +
class MyArray extends Array {
+  // MyArray species를 부모 Array 생성자로 재설정
+  static get [Symbol.species]() { return Array; }
+}
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
명세상태비고
{{SpecName('ES6', '#sec-get-array-@@species', 'get Array [ @@species ]')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-get-array-@@species', 'get Array [ @@species ]')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Array.@@species")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/@@unscopables/index.html b/files/ko/web/javascript/reference/global_objects/array/@@unscopables/index.html new file mode 100644 index 0000000000..1ac7f0b29b --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/@@unscopables/index.html @@ -0,0 +1,72 @@ +--- +title: 'Array.prototype[@@unscopables]' +slug: Web/JavaScript/Reference/Global_Objects/Array/@@unscopables +tags: + - Array + - ECMAScript 2015 + - JavaScript + - Property + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Array/@@unscopables +--- +
{{JSRef}}
+ +

@@unscopable 기호 속성은 ES2015 이전 ECMAScript 표준에 포함되지 않은 속성 이름을 포함합니다. 해당 속성들은 {{jsxref("Statements/with", "with")}} 바인딩에서 제외됩니다.

+ +

구문

+ +
arr[Symbol.unscopables]
+ +

설명

+ +

with 바인딩에서 제외되는 배열의 기본 속성은 copyWithin, entries, fill, find, findIndex, includes, keys, values입니다.

+ +

자신의 객체에 대해 unscopables를 설정하는 방법은 {{jsxref("Symbol.unscopables")}}를 참고하세요.

+ +

{{js_property_attributes (0,0,1)}}

+ +

예제

+ +

아래 코드는 ES5 이하에서 잘 작동합니다. 그러나 ECMAScript 2015 이후 {{jsxref("Array.prototype.keys()")}} 메서드가 도입되었습니다. 이는 with 내부에서 "keys"가 변수가 아니라 메서드임을 의미합니다. 여기서 Array.prototype[@@unscopables]가 개입하여 일부 배열 메서드가 with 범위에 묶이는 일을 방지합니다.

+ +
var keys = [];
+
+with (Array.prototype) {
+  keys.push("something");
+}
+
+Object.keys(Array.prototype[Symbol.unscopables]);
+// ["copyWithin", "entries", "fill", "find", "findIndex",
+//  "includes", "keys", "values"]
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-array.prototype-@@unscopables', 'Array.prototype[@@unscopables]')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.prototype-@@unscopables', 'Array.prototype[@@unscopables]')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

{{Compat("javascript.builtins.Array.@@unscopables")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/array/index.html b/files/ko/web/javascript/reference/global_objects/array/array/index.html new file mode 100644 index 0000000000..3f3d60a4ec --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/array/index.html @@ -0,0 +1,86 @@ +--- +title: Array() 생성자 +slug: Web/JavaScript/Reference/Global_Objects/Array/Array +tags: + - Array + - Constructor + - JavaScript + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/Array +--- +
{{JSRef}}
+ +

Array() 생성자는 새로운 {{jsxref("Array")}} 객체를 생성할 때 사용합니다.

+ +

구문

+ +
[element0, element1, ..., elementN]
+
+new Array(element0, element1[, ...[, elementN]])
+new Array(arrayLength)
+ +

매개변수

+ +
+
elementN
+
JavaScript 배열을 초기화할 때 채워넣을 요소. 단, 항목이 하나 뿐이며 그 항목의 자료형이 숫자일 경우 아래의 arrayLength 매개변수로 간주합니다.
+
arrayLength
+
Array 생성자에 제공한 유일한 매개변수가 0에서 232-1 이하의 정수인 경우, length 속성이 해당 값인 새로운 JavaScript 배열을 생성합니다. (참고: 이렇게 생성한 배열은 arrayLength 만큼의 빈 슬롯을 가지는 것으로, 실제 {{jsxref("undefined")}}를 채우는 것이 아닙니다.) 값이 범위 밖이거나 정수가 아닌 경우 {{jsxref("RangeError")}}가 발생합니다.
+
+ +

예제

+ +

배열 리터럴 표기법

+ +

배열은 리터럴 표기법으로 생성할 수도 있습니다.

+ +
let fruits = ['사과', '바나나']
+
+console.log(fruits.length) // 2
+console.log(fruits[0])     // "사과"
+
+ +

단일 매개변수 배열 생성자

+ +

배열을 생성자와 하나의 숫자 매개변수로 생성할 수 있습니다. 그 결과는 length가 매개변수고, 길이만큼의 빈 슬롯을 가진 배열입니다.

+ +
let fruits = new Array(2)
+
+console.log(fruits.length) // 2
+console.log(fruits[0])     // undefined
+
+ +

복수 매개변수 배열 생성자

+ +

생성자에 두 개 이상의 매개변수를 제공할 경우, 매개변수를 원소로 하는 새로운 배열을 생성합니다.

+ +
let fruits = new Array('사과', '바나나')
+
+console.log(fruits.length) // 2
+console.log(fruits[0])     // "사과"
+
+ +

명세

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-array-constructor', 'Array constructor')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Array.Array")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/concat/index.html b/files/ko/web/javascript/reference/global_objects/array/concat/index.html new file mode 100644 index 0000000000..b35f040632 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/concat/index.html @@ -0,0 +1,138 @@ +--- +title: Array.prototype.concat() +slug: Web/JavaScript/Reference/Global_Objects/Array/concat +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/concat +--- +
{{JSRef}}
+ +

concat() 메서드는 인자로 주어진 배열이나 값들을 기존 배열에 합쳐서 새 배열을 반환합니다. 

+ + + +
{{EmbedInteractiveExample("pages/js/array-concat.html")}}
+ + + +

구문

+ +
array.concat([value1[, value2[, ...[, valueN]]]])
+ +

매개변수

+ + + +
+
valueN {{optional_inline}}
+
자세한 내용은 아래 설명을 참고하세요.
+
+ +

반환값

+ +

새로운 {{jsxref("Array")}} 객체.

+ +

설명

+ +

concat은 메서드를 호출한 배열 뒤에 각 인수를 순서대로 붙여 새로운 배열을 만듭니다. 인수가 배열이면 그 구성요소가 순서대로 붙고, 배열이 아니면 인수 자체가 붙습니다. 중첩 배열 내부로 재귀하지 않습니다.

+ +

concatthis나 인수로 넘겨진 배열의 내용을 바꾸지 않고, 대신 주어진 배열을 합친 뒤 그 얕은 사본을 반환합니다. 새 배열에는 원본 배열의 요소를 다음과 같은 방법으로 복사합니다.

+ + + +
+

참고: 배열이나 값을 이어붙여도 원본은 변하지 않으며, 새로운 배열이나 원본 배열을 조작해도 서로 영향을 받지 않습니다.

+
+ +

예제

+ +

배열 두 개 이어붙이기

+ +

다음 예제는 두 개의 배열을 이어붙입니다.

+ +
const alpha = ['a', 'b', 'c'];
+const numeric = [1, 2, 3];
+
+alpha.concat(numeric);
+// 결과: ['a', 'b', 'c', 1, 2, 3]
+
+ +

배열 세 개 이어붙이기

+ +

다음 예제는 세 개의 배열을 이어붙입니다.

+ +
const num1 = [1, 2, 3];
+const num2 = [4, 5, 6];
+const num3 = [7, 8, 9];
+
+num1.concat(num2, num3);
+// 결과: [1, 2, 3, 4, 5, 6, 7, 8, 9]
+
+ +

배열에 값 이어붙이기

+ +

다음 코드는 배열에 세 개의 값을 이어붙입니다.

+ +
const alpha = ['a', 'b', 'c'];
+
+alpha.concat(1, [2, 3]);
+// 결과: ['a', 'b', 'c', 1, 2, 3]
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
표준상태비고
{{SpecName('ES3')}}{{Spec2('ES3')}}최초 정의. JavaScript 1.2에서 구현됨.
{{SpecName('ES5.1', '#sec-15.4.4.4', 'Array.prototype.concat')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-array.prototype.concat', 'Array.prototype.concat')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.concat', 'Array.prototype.concat')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ +
{{Compat("javascript.builtins.Array.concat")}}
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/copywithin/index.html b/files/ko/web/javascript/reference/global_objects/array/copywithin/index.html new file mode 100644 index 0000000000..7d6c2cdf8b --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/copywithin/index.html @@ -0,0 +1,183 @@ +--- +title: Array.prototype.copyWithin() +slug: Web/JavaScript/Reference/Global_Objects/Array/copyWithin +tags: + - Array + - ECMAScript 2015 + - JavaScript + - Method + - Prototype + - Reference + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/copyWithin +--- +
{{JSRef}}
+ +

copyWithin() 메서드는 배열의 일부를 얕게 복사한 뒤, 동일한 배열의 다른 위치에 덮어쓰고 그 배열을 반환합니다. 이 때, 크기(배열의 길이)를 수정하지 않고 반환합니다.

+ +

{{EmbedInteractiveExample("pages/js/array-copywithin.html")}}

+ +

구문

+ +
arr.copyWithin(target[, start[, end]])
+
+ +

매개변수

+ +
+
target
+
복사한 시퀀스(값)를 넣을 위치를 가리키는 0 기반 인덱스. 음수를 지정하면 인덱스를 배열의 끝에서부터 계산합니다.
+
+ targetarr.length보다 크거나 같으면 아무것도 복사하지 않습니다. targetstart 이후라면 복사한 시퀀스를 arr.length에 맞춰 자릅니다.
+
start {{optional_inline}}
+
복사를 시작할 위치를 가리키는 0 기반 인덱스. 음수를 지정하면 인덱스를 배열의 끝에서부터 계산합니다.
+
+ 기본값은 0으로, start를 지정하지 않으면 배열의 처음부터 복사합니다.
+
end {{optional_inline}}
+
복사를 끝낼 위치를 가리키는 0 기반 인덱스. copyWithinend 인덱스 이전까지 복사하므로 end 인덱스가 가리키는 요소는 제외합니다. 음수를 지정하면 인덱스를 배열의 끝에서부터 계산합니다.
+
+ 기본값은 arr.length로, end를 지정하지 않으면 배열의 끝까지 복사합니다.
+
+ +

반환 값

+ +

수정한 배열.

+ +

설명

+ +

copyWithin은 C와 C++의 memmove처럼 작동하고, 복사와 대입이 하나의 연산에서 이루어지므로 {{jsxref("Array")}}의 데이터를 이동할 때 사용할 수 있는 고성능 메서드입니다. {{jsxref("TypedArray.prototype.copyWithin()", "TypedArray")}}의 동명 메서드에서 이 특징이 두드러집니다. 붙여넣은 시퀀스의 위치가 복사한 범위와 겹치더라도 최종 결과는 원본 배열에서 복사한 것과 같습니다.

+ +

copyWithin 함수는 제네릭 함수로, this 값이 {{jsxref("Array")}} 객체일 필요는 없습니다.

+ +

copyWithin 메서드는 변경자 메서드로, this의 길이는 바꾸지 않지만 내용을 바꾸며 필요하다면 새로운 속성을 생성합니다.

+ +

예제

+ +
[1, 2, 3, 4, 5].copyWithin(-2);
+// [1, 2, 3, 1, 2]
+
+[1, 2, 3, 4, 5].copyWithin(0, 3);
+// [4, 5, 3, 4, 5]
+
+[1, 2, 3, 4, 5].copyWithin(0, 3, 4);
+// [4, 2, 3, 4, 5]
+
+[1, 2, 3, 4, 5].copyWithin(-2, -3, -1);
+// [1, 2, 3, 3, 4]
+
+[].copyWithin.call({length: 5, 3: 1}, 0, 3);
+// {0: 1, 3: 1, length: 5}
+
+// ES2015 TypedArray는 Array의 하위 클래스
+var i32a = new Int32Array([1, 2, 3, 4, 5]);
+
+i32a.copyWithin(0, 2);
+// Int32Array [3, 4, 5, 4, 5]
+
+// 아직 ES2015를 사용할 수 없는 환경에서
+[].copyWithin.call(new Int32Array([1, 2, 3, 4, 5]), 0, 3, 4);
+// Int32Array [4, 2, 3, 4, 5]
+
+ +

폴리필

+ +
if (!Array.prototype.copyWithin) {
+  Array.prototype.copyWithin = function(target, start/*, end*/) {
+    // Steps 1-2.
+    if (this == null) {
+      throw new TypeError('this is null or not defined');
+    }
+
+    var O = Object(this);
+
+    // Steps 3-5.
+    var len = O.length >>> 0;
+
+    // Steps 6-8.
+    var relativeTarget = target >> 0;
+
+    var to = relativeTarget < 0 ?
+      Math.max(len + relativeTarget, 0) :
+      Math.min(relativeTarget, len);
+
+    // Steps 9-11.
+    var relativeStart = start >> 0;
+
+    var from = relativeStart < 0 ?
+      Math.max(len + relativeStart, 0) :
+      Math.min(relativeStart, len);
+
+    // Steps 12-14.
+    var end = arguments[2];
+    var relativeEnd = end === undefined ? len : end >> 0;
+
+    var final = relativeEnd < 0 ?
+      Math.max(len + relativeEnd, 0) :
+      Math.min(relativeEnd, len);
+
+    // Step 15.
+    var count = Math.min(final - from, len - to);
+
+    // Steps 16-17.
+    var direction = 1;
+
+    if (from < to && to < (from + count)) {
+      direction = -1;
+      from += count - 1;
+      to += count - 1;
+    }
+
+    // Step 18.
+    while (count > 0) {
+      if (from in O) {
+        O[to] = O[from];
+      } else {
+        delete O[to];
+      }
+
+      from += direction;
+      to += direction;
+      count--;
+    }
+
+    // Step 19.
+    return O;
+  };
+}
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-array.prototype.copywithin', 'Array.prototype.copyWithin')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ES7', '#sec-array.prototype.copywithin', 'Array.prototype.copyWithin')}}{{Spec2('ES7')}} 
{{SpecName('ESDraft', '#sec-array.prototype.copywithin', 'Array.prototype.copyWithin')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +
{{Compat("javascript.builtins.Array.copyWithin")}}
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/entries/index.html b/files/ko/web/javascript/reference/global_objects/array/entries/index.html new file mode 100644 index 0000000000..316886c261 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/entries/index.html @@ -0,0 +1,89 @@ +--- +title: Array.prototype.entries() +slug: Web/JavaScript/Reference/Global_Objects/Array/entries +tags: + - Array + - ECMAScript 2015 + - Iterator + - JavaScript + - Method + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Array/entries +--- +
{{JSRef}}
+ +

entries() 메서드는 배열의 각 인덱스에 대한 키/값 쌍을 가지는 새로운 Array Iterator 객체를 반환합니다.

+ +

{{EmbedInteractiveExample("pages/js/array-entries.html")}}

+ + + +

구문

+ +
arr.entries()
+
+ +

반환 값

+ +

{{jsxref("Array")}} 반복자 인스턴스 객체.

+ +

예시

+ +

인덱스와 요소 이터레이팅

+ +
const a = ['a', 'b', 'c'];
+
+for (const [index, element] of a.entries())
+  console.log(index, element);
+
+// 0 'a'
+// 1 'b'
+// 2 'c'
+ +

for…of 루프 사용

+ +
var a = ['a', 'b', 'c'];
+var iterator = a.entries();
+
+for (let e of iterator) {
+  console.log(e);
+}
+// [0, 'a']
+// [1, 'b']
+// [2, 'c']
+
+ +

Specifications

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-array.prototype.entries', 'Array.prototype.entries')}}
+ +

브라우저 호환성

+ +
+ + +

{{Compat("javascript.builtins.Array.entries")}}

+
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/every/index.html b/files/ko/web/javascript/reference/global_objects/array/every/index.html new file mode 100644 index 0000000000..827b81e760 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/every/index.html @@ -0,0 +1,191 @@ +--- +title: Array.prototype.every() +slug: Web/JavaScript/Reference/Global_Objects/Array/every +tags: + - Array + - ECMAScript 5 + - JavaScript + - Method + - Prototype + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/every +--- +
{{JSRef}}
+ +

every() 메서드는 배열 안의 모든 요소가 주어진 판별 함수를 통과하는지 테스트합니다.

+ +
+

참고: 빈 배열에서 호출하면 무조건 true를 반환합니다.

+
+ +
{{EmbedInteractiveExample("pages/js/array-every.html")}}
+ + + +

구문

+ +
arr.every(callback[, thisArg])
+ +

매개변수

+ +
+
callback
+
각 요소를 시험할 함수. 다음 세 가지 인수를 받습니다. +
+
currentValue
+
처리할 현재 요소.
+
index {{Optional_inline}}
+
처리할 현재 요소의 인덱스.
+
array {{Optional_inline}}
+
every를 호출한 배열.
+
+
+
thisArg {{Optional_inline}}
+
callback을 실행할 때 this로 사용하는 값.
+
+ +

반환 값

+ +

callback이 모든 배열 요소에 대해 참({{Glossary("truthy")}})인 값을 반환하는 경우 true, 그 외엔 false.

+ +

설명

+ +

everycallback이 {{glossary("falsy", "거짓")}}을 반환하는 요소를 찾을 때까지 배열에 있는 각 요소에 대해 한 번씩 callback 함수를 실행합니다. 해당하는 요소를 발견한 경우 every는 즉시 false를 반환합니다. 그렇지 않으면, 즉 모든 값에서 참을 반환하면 true를 반환합니다. 할당한 값이 있는 배열의 인덱스에서만 callback을 호출합니다. 삭제했거나 값을 할당한 적이 없는 인덱스에서는 호출하지 않습니다.

+ +

callback은 요소의 값, 해당 요소의 인덱스 및 순회하고 있는 배열 세 가지 인수와 함께 호출됩니다.

+ +

thisArg 매개변수를 every에 제공한 경우 callbackthis로 사용됩니다. 그 외엔 {{jsxref("undefined")}}값을 사용합니다. 최종적으로 callback이 볼 수 있는 this의 값은 함수가 볼 수 있는 this를 결정하는 평소 규칙을 따릅니다.

+ +

every는 호출한 배열을 변형하지 않습니다.

+ +

every가 처리하는 요소의 범위는 callback의 첫 호출 전에 설정됩니다. every 호출 이후로 배열에 추가하는 요소는 callback이 방문하지 않습니다. 배열에 원래 있었지만 아직 방문하지 않은 요소가 callback에 의해 변경된 경우, 그 인덱스를 방문하는 시점의 값을 사용합니다. 삭제한 요소는 방문하지 않습니다.

+ +

every는 (이산)수학에서 전칭(∀) 정량자quantifier(한정자)처럼 행동합니다. 특히, 빈 배열에 대해서는 true를 반환합니다. (이는 공집합의 모든 요소가 어떠한 주어진 조건도 만족하는 공허한 참입니다.)

+ +

예제

+ +

모든 배열 요소의 크기 테스트

+ +

다음 예는 배열의 모든 요소가 10보다 더 큰지 테스트합니다.

+ +
function isBigEnough(element, index, array) {
+  return element >= 10;
+}
+[12, 5, 8, 130, 44].every(isBigEnough);   // false
+[12, 54, 18, 130, 44].every(isBigEnough); // true
+
+ +

화살표 함수 사용

+ +

화살표 함수는 같은 테스트에 대해 더 짧은 구문을 제공합니다.

+ +
[12, 5, 8, 130, 44].every(elem => elem >= 10); // false
+[12, 54, 18, 130, 44].every(elem => elem >= 10); // true
+ +

폴리필

+ +

every는 ECMA-262 표준 제5판에 추가됐으므로 어떤 표준 구현체에서는 사용하지 못할 수도 있습니다. 다른 모든 코드 이전에 아래 코드를 포함하면 every를 지원하지 않는 환경에서도 사용할 수 있습니다. 아래 알고리즘은 {{jsxref("Object")}}와 {{jsxref("TypeError")}}가 변형되지 않고, callbackfn.call의 계산 값이 원래의 {{jsxref("Function.prototype.call()")}}과 같은 경우 ECMA-262 제5판이 명시한 것과 동일합니다.

+ +
if (!Array.prototype.every) {
+  Array.prototype.every = function(callbackfn, thisArg) {
+    'use strict';
+    var T, k;
+
+    if (this == null) {
+      throw new TypeError('this is null or not defined');
+    }
+
+    // 1. Let O be the result of calling ToObject passing the this
+    //    value as the argument.
+    var O = Object(this);
+
+    // 2. Let lenValue be the result of calling the Get internal method
+    //    of O with the argument "length".
+    // 3. Let len be ToUint32(lenValue).
+    var len = O.length >>> 0;
+
+    // 4. If IsCallable(callbackfn) is false, throw a TypeError exception.
+    if (typeof callbackfn !== 'function') {
+      throw new TypeError();
+    }
+
+    // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
+    if (arguments.length > 1) {
+      T = thisArg;
+    }
+
+    // 6. Let k be 0.
+    k = 0;
+
+    // 7. Repeat, while k < len
+    while (k < len) {
+
+      var kValue;
+
+      // a. Let Pk be ToString(k).
+      //   This is implicit for LHS operands of the in operator
+      // b. Let kPresent be the result of calling the HasProperty internal
+      //    method of O with argument Pk.
+      //   This step can be combined with c
+      // c. If kPresent is true, then
+      if (k in O) {
+
+        // i. Let kValue be the result of calling the Get internal method
+        //    of O with argument Pk.
+        kValue = O[k];
+
+        // ii. Let testResult be the result of calling the Call internal method
+        //     of callbackfn with T as the this value and argument list
+        //     containing kValue, k, and O.
+        var testResult = callbackfn.call(T, kValue, k, O);
+
+        // iii. If ToBoolean(testResult) is false, return false.
+        if (!testResult) {
+          return false;
+        }
+      }
+      k++;
+    }
+    return true;
+  };
+}
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('ES5.1', '#sec-15.4.4.16', 'Array.prototype.every')}}{{Spec2('ES5.1')}}초기 정의. JavaScript 1.6에서 구현됨.
{{SpecName('ES6', '#sec-array.prototype.every', 'Array.prototype.every')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.every', 'Array.prototype.every')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

{{Compat("javascript.builtins.Array.every")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/fill/index.html b/files/ko/web/javascript/reference/global_objects/array/fill/index.html new file mode 100644 index 0000000000..5a18af7d24 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/fill/index.html @@ -0,0 +1,146 @@ +--- +title: Array.prototype.fill() +slug: Web/JavaScript/Reference/Global_Objects/Array/fill +tags: + - Array + - ECMAScript 2015 + - JavaScript + - Method + - Prototype + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/fill +--- +
{{JSRef}}
+ +

fill() 메서드는 배열의 시작 인덱스부터 끝 인덱스의 이전까지 정적인 값 하나로 채웁니다.

+ +

{{EmbedInteractiveExample("pages/js/array-fill.html")}}

+ +

구문

+ +
arr.fill(value[, start[, end]])
+ +

매개변수

+ +
+
value
+
배열을 채울 값.
+
start {{optional_inline}}
+
시작 인덱스, 기본 값은 0.
+
end {{optional_inline}}
+
끝 인덱스, 기본 값은 this.length.
+
+ +

반환 값

+ +

변형한 배열.

+ +

설명 

+ +

fill 메서드는 value, startend의 3개 인자를 가집니다. startend 인자는 선택 사항으로써 기본값으로 각각 0과, this 객체의 length를 가집니다.

+ +

length가 배열의 길이일 때, start가 음수이면 시작 인덱스는 length+start입니다. end가 음수이면 끝 인덱스는 length+end입니다.

+ +

fill은 일반 함수이며, this 값이 배열 객체일 필요는 없습니다.

+ +

fill 메서드는 변경자 메서드로, 복사본이 아니라 this 객체를 변형해 반환합니다.

+ +

value에 객체를 받을 경우 그 참조만 복사해서 배열을 채웁니다.

+ +

예제

+ +
[1, 2, 3].fill(4);               // [4, 4, 4]
+[1, 2, 3].fill(4, 1);            // [1, 4, 4]
+[1, 2, 3].fill(4, 1, 2);         // [1, 4, 3]
+[1, 2, 3].fill(4, 1, 1);         // [1, 2, 3]
+[1, 2, 3].fill(4, 3, 3);         // [1, 2, 3]
+[1, 2, 3].fill(4, -3, -2);       // [4, 2, 3]
+[1, 2, 3].fill(4, NaN, NaN);     // [1, 2, 3]
+[1, 2, 3].fill(4, 3, 5);         // [1, 2, 3]
+Array(3).fill(4);                // [4, 4, 4]
+[].fill.call({ length: 3 }, 4);  // {0: 4, 1: 4, 2: 4, length: 3}
+
+// Objects by reference.
+var arr = Array(3).fill({}); // [{}, {}, {}]
+arr[0].hi = "hi"; // [{ hi: "hi" }, { hi: "hi" }, { hi: "hi" }]
+
+ +

폴리필

+ +
if (!Array.prototype.fill) {
+  Object.defineProperty(Array.prototype, 'fill', {
+    value: function(value) {
+
+      // Steps 1-2.
+      if (this == null) {
+        throw new TypeError('this is null or not defined');
+      }
+
+      var O = Object(this);
+
+      // Steps 3-5.
+      var len = O.length >>> 0;
+
+      // Steps 6-7.
+      var start = arguments[1];
+      var relativeStart = start >> 0;
+
+      // Step 8.
+      var k = relativeStart < 0 ?
+        Math.max(len + relativeStart, 0) :
+        Math.min(relativeStart, len);
+
+      // Steps 9-10.
+      var end = arguments[2];
+      var relativeEnd = end === undefined ?
+        len : end >> 0;
+
+      // Step 11.
+      var final = relativeEnd < 0 ?
+        Math.max(len + relativeEnd, 0) :
+        Math.min(relativeEnd, len);
+
+      // Step 12.
+      while (k < final) {
+        O[k] = value;
+        k++;
+      }
+
+      // Step 13.
+      return O;
+    }
+  });
+}
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-array.prototype.fill', 'Array.prototype.fill')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.prototype.fill', 'Array.prototype.fill')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +
{{Compat("javascript.builtins.Array.fill")}}
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/filter/index.html b/files/ko/web/javascript/reference/global_objects/array/filter/index.html new file mode 100644 index 0000000000..9d1b623fd0 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/filter/index.html @@ -0,0 +1,231 @@ +--- +title: Array.prototype.filter() +slug: Web/JavaScript/Reference/Global_Objects/Array/filter +tags: + - Array + - ECMAScript 5 + - JavaScript + - Method + - Prototype + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/filter +--- +
{{JSRef}}
+ +

filter() 메서드는 주어진 함수의 테스트를 통과하는 모든 요소를 모아 새로운 배열로 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/array-filter.html")}}
+ + + +

구문

+ +
arr.filter(callback(element[, index[, array]])[, thisArg])
+ +

매개변수

+ +
+
callback
+
각 요소를 시험할 함수. true를 반환하면 요소를 유지하고, false를 반환하면 버립니다. 다음 세 가지 매개변수를 받습니다.
+
+
+
element
+
처리할 현재 요소.
+
index {{optional_inline}}
+
처리할 현재 요소의 인덱스.
+
array {{optional_inline}}
+
filter를 호출한 배열.
+
+
+
thisArg {{optional_inline}}
+
callback을 실행할 때 this로 사용하는 값.
+
+ +

반환 값

+ +

테스트를 통과한 요소로 이루어진 새로운 배열. 어떤 요소도 테스트를 통과하지 못했으면 빈 배열을 반환합니다.

+ +

설명

+ +

filter()는 배열 내 각 요소에 대해 한 번 제공된 callback 함수를 호출해, callbacktrue로 강제하는 값을 반환하는 모든 값이 있는 새로운 배열을 생성합니다. callback은 할당된 값이 있는 배열의 인덱스에 대해서만 호출됩니다; 삭제됐거나 값이 할당된 적이 없는 인덱스에 대해서는 호출되지 않습니다. callback 테스트를 통과하지 못한 배열 요소는 그냥 건너뛰며 새로운 배열에 포함되지 않습니다.

+ +

callback은 다음 세 인수와 함께 호출됩니다:

+ +
    +
  1. 요소값
  2. +
  3. 요소 인덱스
  4. +
  5. 순회(traverse)되는 배열 객체
  6. +
+ +

thisArg 매개변수가 filter에 제공된 경우, 호출될 때 그 값은 callbackthis 값으로 전달됩니다.  그 이외에, undefined값도 callback의 this 값으로 쓰기 위해 전달됩니다. 결국 callback에 의해 관찰될 수 있는 this 값은 this를 결정하는 함수의 평소 규칙에 따라 결정됩니다.

+ +

filter()는 호출되는 배열을 변화시키지(mutate) 않습니다.

+ +

filter()에 의해 처리되는 요소의 범위는 callback의 첫 호출 전에 설정됩니다. filter() 호출 시작 이후로 배열에 추가된 요소는 callback에 의해 방문되지 않습니다. 배열의 기존 요소가 변경 또는 삭제된 경우, callback에 전달된 그 값은 filter()가 그 요소를 방문한 시점에 값이 됩니다; 삭제된 요소는 반영되지 않습니다.

+ +

예제

+ +

모든 작은 값 걸러내기

+ +

다음 예는 값이 10 이하인 모든 요소가 제거된 걸러진 배열을 만들기 위해 filter()를 사용합니다.

+ +
function isBigEnough(value) {
+  return value >= 10;
+}
+
+var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
+// filtered 는 [12, 130, 44]
+
+ +

JSON에서 무효한 항목 거르기

+ +

다음 예는 0이 아닌, 숫자 id인 모든 요소의 걸러진 json을 만들기 위해 filter()를 사용합니다.

+ +
var arr = [
+  { id: 15 },
+  { id: -1 },
+  { id: 0 },
+  { id: 3 },
+  { id: 12.2 },
+  { },
+  { id: null },
+  { id: NaN },
+  { id: 'undefined' }
+];
+
+var invalidEntries = 0;
+
+function isNumber(obj) {
+  return obj !== undefined && typeof(obj) === 'number' && !isNaN(obj);
+}
+
+function filterByID(item) {
+  if (isNumber(item.id) && item.id !== 0) {
+    return true;
+  }
+  invalidEntries++;
+  return false;
+}
+
+var arrByID = arr.filter(filterByID);
+
+console.log('Filtered Array\n', arrByID);
+// Filtered Array
+// [{ id: 15 }, { id: -1 }, { id: 3 }, { id: 12.2 }]
+
+console.log('Number of Invalid Entries = ', invalidEntries);
+// Number of Invalid Entries = 5
+
+ +

배열 내용 검색

+ +

다음 예는 배열 내용을 조건에 따라 검색하기 위해 filter() 를 사용합니다.

+ +
var fruits = ['apple', 'banana', 'grapes', 'mango', 'orange'];
+
+/**
+ * 검색 조건에 따른 배열 필터링(쿼리)
+ */
+function filterItems(query) {
+  return fruits.filter(function(el) {
+      return el.toLowerCase().indexOf(query.toLowerCase()) > -1;
+  })
+}
+
+console.log(filterItems('ap')); // ['apple', 'grapes']
+console.log(filterItems('an')); // ['banana', 'mango', 'orange']
+ +

ES2015로 구현

+ +
const fruits = ['apple', 'banana', 'grapes', 'mango', 'orange'];
+
+/**
+ * 검색 조건에 따른 배열 필터링(쿼리)
+ */
+const filterItems = (query) => {
+  return fruits.filter((el) =>
+    el.toLowerCase().indexOf(query.toLowerCase()) > -1
+  );
+}
+
+console.log(filterItems('ap')); // ['apple', 'grapes']
+console.log(filterItems('an')); // ['banana', 'mango', 'orange']
+ +

폴리필

+ +

filter는 ECMA-262 표준 제5판에 추가됐습니다. 따라서 어떤 표준 구현체에서는 사용할 수 없을 수도 있습니다. 다른 모든 코드 이전에 아래 코드를 포함하면 지원하지 않는 환경에서도 filter를 사용할 수 있습니다. 아래 알고리즘은 fn.call의 계산 값이 원래의 Function.prototype.call()과 같고, {{jsxref("Array.prototype.push()")}}가 변형되지 않은 경우 ECMA-262 제5판이 명시한 것과 동일합니다.

+ +
if (!Array.prototype.filter){
+  Array.prototype.filter = function(func, thisArg) {
+    'use strict';
+    if ( ! ((typeof func === 'Function' || typeof func === 'function') && this) )
+        throw new TypeError();
+
+    var len = this.length >>> 0,
+        res = new Array(len), // preallocate array
+        t = this, c = 0, i = -1;
+    if (thisArg === undefined){
+      while (++i !== len){
+        // checks to see if the key was set
+        if (i in this){
+          if (func(t[i], i, t)){
+            res[c++] = t[i];
+          }
+        }
+      }
+    }
+    else{
+      while (++i !== len){
+        // checks to see if the key was set
+        if (i in this){
+          if (func.call(thisArg, t[i], i, t)){
+            res[c++] = t[i];
+          }
+        }
+      }
+    }
+
+    res.length = c; // shrink down array to proper size
+    return res;
+  };
+}
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('ES5.1', '#sec-15.4.4.20', 'Array.prototype.filter')}}{{Spec2('ES5.1')}}초기 정의. JavaScript 1.6에서 구현됨.
{{SpecName('ES6', '#sec-array.prototype.filter', 'Array.prototype.filter')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.filter', 'Array.prototype.filter')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ +

{{Compat("javascript.builtins.Array.filter")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/find/index.html b/files/ko/web/javascript/reference/global_objects/array/find/index.html new file mode 100644 index 0000000000..92a0208a6b --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/find/index.html @@ -0,0 +1,226 @@ +--- +title: Array.prototype.find() +slug: Web/JavaScript/Reference/Global_Objects/Array/find +tags: + - Array + - ECMAScript 2015 + - JavaScript + - Method + - Prototype + - Reference + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/find +--- +
{{JSRef}}
+ +

find() 메서드는 주어진 판별 함수를 만족하는 첫 번째 요소을 반환합니다. 그런 요소가 없다면 {{jsxref("undefined")}}를 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/array-find.html")}}
+ + + +

찾은 요소의 값 대신 인덱스를 반환하는 {{jsxref("Array.findIndex", "findIndex()")}} 메서드도 살펴보세요.

+ +

배열 요소의 위치를 찾고자 하는 경우에는 {{jsxref("Array.prototype.indexOf()")}}를 사용하세요.

+ +

배열 요소가 해당 배열에 존재하는지 확인하고자 하는 경우에는 {{jsxref("Array.prototype.indexOf()")}} 또는 {{jsxref("Array.prototype.includes()")}}를 사용세요.

+ +

구문

+ +
arr.find(callback[, thisArg])
+ +

매개변수

+ +
+
callback
+
배열의 각 값에 대해 실행할 함수. 아래의 세 인자를 받습니다. +
+
element
+
콜백함수에서 처리할 현재 요소.
+
index{{optional_inline}}
+
콜백함수에서 처리할 현재 요소의 인덱스.
+
array{{optional_inline}}
+
find 함수를 호출한 배열.
+
+
+
thisArg
+
선택 항목. 콜백이 호출될 때 this로 사용할 객체.
+
+ +

반환 값

+ +

주어진 판별 함수를 만족하는 첫 번째 요소. 그 외에는 {{jsxref("undefined")}}.

+ +

설명

+ +

find 메서드는 callback 함수가 참을 반환 할 때까지 해당 배열의 각 요소에 대해서 callback 함수를 실행합니다. 만약 어느 요소를 찾았다면 find 메서드는 해당 요소의 값을 즉시 반환하고, 그렇지 않았다면 {{jsxref("undefined")}}를 반환합니다. callback0 부터 length - 1 까지 배열의 모든 인덱스에 대해 호출되며, 값이 지정되지 않은 요소도 포함하여 모든 인덱스에 대해 호출됩니다. 따라서, 희소 배열 (sparse arrays)의 경우에는 값이 지정된 요소만 탐색하는 다른 메소드에 비해 더 비효율적입니다.

+ +

callback은 다음의 세가지 인자를 가지고 호출됩니다: 요소의 값, 요소의 인덱스, 순회의 대상이 되는 배열. 

+ +

thisArg 파라미터가 주어진 경우에는 제공되었다면  thisArgcallback안에서 this로 사용되고, 그렇지 않은 경우 {{jsxref("undefined")}} 가 this로 사용됩니다. 

+ +

find는 호출의 대상이 된 배열을 변경(mutate)하지 않습니다.

+ +

find가 처리할 배열 요소의 범위는 첫 callback이 호출되기 전에 먼저 결정됩니다. find메서드가 실행 된 이후에 배열에 추가된 요소들에 대해서는 callback이 호출되지 않습니다. 아직 callback이 호출되지 않았던 배열 요소가 callback에 의해서 변경된 경우, find가 해당 요소의 인덱스를 방문할 때의 값으로 callback함수에 전달될 것입니다. 즉, 삭제된 요소에도 callback이 호출됩니다.

+ +

예제

+ +

속성 중 하나를 사용하여 배열에서 객체 찾기

+ +
var inventory = [
+    {name: 'apples', quantity: 2},
+    {name: 'bananas', quantity: 0},
+    {name: 'cherries', quantity: 5}
+];
+
+function findCherries(fruit) {
+    return fruit.name === 'cherries';
+}
+
+console.log(inventory.find(findCherries)); // { name: 'cherries', quantity: 5 }
+
+ +

ES2015 화살표 함수 사용하기

+ +

 

+ +
const inventory = [
+    {name: 'apples', quantity: 2},
+    {name: 'bananas', quantity: 0},
+    {name: 'cherries', quantity: 5}
+];
+
+const result = inventory.find(fruit => fruit.name === 'cherries');
+
+console.log(result) // { name: 'cherries', quantity: 5 }
+ +

 

+ +

배열에서 소수 찾기

+ +

다음 예제에서는 배열의 요소 중 소수인 요소를 찾습니다(소수가 없는 경우에는 {{jsxref("undefined")}}를 반환).

+ +
function isPrime(element, index, array) {
+  var start = 2;
+  while (start <= Math.sqrt(element)) {
+    if (element % start++ < 1) {
+      return false;
+    }
+  }
+  return element > 1;
+}
+
+console.log([4, 6, 8, 12].find(isPrime)); // undefined, not found
+console.log([4, 5, 8, 12].find(isPrime)); // 5
+
+ +

탐색 중 삭제된 배열 요소

+ +

다음 예제에서는 삭제되어 존재하지 않는 배열의 요소에도 callback이 호출되어 해당 시점의 값이 callback에 전달되는 것을 보여줍니다.

+ +
// Declare array with no element at index 2, 3 and 4
+var a = [0,1,,,,5,6];
+
+// Shows all indexes, not just those that have been assigned values
+a.find(function(value, index) {
+  console.log('Visited index ' + index + ' with value ' + value);
+});
+// Shows all indexes, including deleted
+  a.find(function(value, index) {
+  // Delete element 5 on first iteration
+  if (index == 0) {
+    console.log('Deleting a[5] with value ' + a[5]);
+    delete a[5];
+  }
+  // Element 5 is still visited even though deleted
+  console.log('Visited index ' + index + ' with value ' + value);
+});
+
+ +

폴리필

+ +

find는 ECMAScript 2015 명세에 추가됐으므로 어떤 표준 구현체에서는 사용지 못할 수도 있습니다. 다른 모든 코드 이전에 아래 코드를 포함하면 find를 지원하지 않는 환경에서도 사용할 수 있습니다.

+ +
// https://tc39.github.io/ecma262/#sec-array.prototype.find
+if (!Array.prototype.find) {
+  Object.defineProperty(Array.prototype, 'find', {
+    value: function(predicate) {
+     // 1. Let O be ? ToObject(this value).
+      if (this == null) {
+        throw new TypeError('"this" is null or not defined');
+      }
+
+      var o = Object(this);
+
+      // 2. Let len be ? ToLength(? Get(O, "length")).
+      var len = o.length >>> 0;
+
+      // 3. If IsCallable(predicate) is false, throw a TypeError exception.
+      if (typeof predicate !== 'function') {
+        throw new TypeError('predicate must be a function');
+      }
+
+      // 4. If thisArg was supplied, let T be thisArg; else let T be undefined.
+      var thisArg = arguments[1];
+
+      // 5. Let k be 0.
+      var k = 0;
+
+      // 6. Repeat, while k < len
+      while (k < len) {
+        // a. Let Pk be ! ToString(k).
+        // b. Let kValue be ? Get(O, Pk).
+        // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)).
+        // d. If testResult is true, return kValue.
+        var kValue = o[k];
+        if (predicate.call(thisArg, kValue, k, o)) {
+          return kValue;
+        }
+        // e. Increase k by 1.
+        k++;
+      }
+
+      // 7. Return undefined.
+      return undefined;
+    },
+    configurable: true,
+    writable: true
+  });
+}
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-array.prototype.find', 'Array.prototype.find')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.prototype.find', 'Array.prototype.find')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +
{{Compat("javascript.builtins.Array.find")}}
+ +
 
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/findindex/index.html b/files/ko/web/javascript/reference/global_objects/array/findindex/index.html new file mode 100644 index 0000000000..9406439e6a --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/findindex/index.html @@ -0,0 +1,146 @@ +--- +title: Array.prototype.findIndex() +slug: Web/JavaScript/Reference/Global_Objects/Array/findIndex +tags: + - Array + - ECMAScript 2015 + - JavaScript + - Method + - Prototype + - Reference + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/findIndex +--- +
{{JSRef}}
+ +

findIndex() 메서드는 주어진 판별 함수를 만족하는 배열의 첫 번째 요소에 대한 인덱스를 반환합니다. 만족하는 요소가 없으면 -1을 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/array-findindex.html")}}
+ + + +

인덱스 대신 을 반환하는 {{jsxref("Array.prototype.find", "find()")}} 메서드도 참고하세요.

+ +

구문

+ +
arr.findIndex(callback(element[, index[, array]])[, thisArg])
+ +

매개변수

+ +
+
callback
+
3개의 인수를 취하여 배열의 각 값에 대해 실행할 함수입니다.
+
+
+
element
+
배열에서 처리중인 현재 요소입니다.
+
index
+
배열에서 처리중인 현재 요소의 인덱스입니다.
+
array
+
findIndex 함수가 호출된 배열입니다.
+
+
+
thisArg
+
선택 사항. 콜백을 실행할 때 this로 사용할 객체입니다.
+
+ +

반환 값

+ +

요소가 테스트를 통과하면 배열의 인덱스. 그렇지 않으면 -1입니다.

+ +

설명

+ +

findIndex 메서드는 콜백 함수가 진리 값 (true를 반환하는 값)을 반환 할 때까지 배열의 모든 배열 인덱스 0..length-1 (포함)에 대해 한 번씩 콜백 함수를 실행합니다. 이러한 요소가 발견되면 findIndex는 해당 반복에 대한 색인을 즉시 반환합니다. 콜백이 진리 값을 반환하지 않거나 배열의 길이가 0 인 경우 findIndex는 -1을 반환합니다. Array # some과 같은 다른 배열 메소드와는 달리, 배열에 존재하지 않는 엔트리의 인덱스에 대해서조차 콜백이 호출됩니다.

+ +

콜백은 요소의 값, 요소의 인덱스 및 가로 지르는 Array 객체의 세 가지 인수로 호출됩니다.

+ +

thisArg 매개 변수가 findIndex에 제공되면 콜백 호출마다 thisArg 매개 변수가 사용됩니다. 제공되지 않으면 {{jsxref ( "undefined")}}가 사용됩니다.

+ +

findIndex는 호출 된 배열을 변경하지 않습니다.

+ +

findIndex에 의해 처리되는 요소의 범위는 콜백의 첫 번째 호출 전에 설정됩니다. findIndex 호출이 시작된 후 배열에 추가되는 요소는 콜백에 의해 방문되지 않습니다. 배열의 기존의 방문하지 않은 요소가 콜백에 의해 변경되면 방문 콜백에 전달 된 값은 findIndex가 해당 요소의 인덱스를 방문 할 때의 값이됩니다. 삭제된 요소도 방문합니다.

+ +

예제

+ +

배열에서 소수의 색인 찾기

+ +

다음 예제에서는 배열에서 소수 (소수가없는 경우 -1을 반환) 인 요소의 인덱스를 찾습니다.

+ +
function isPrime(element, index, array) {
+  var start = 2;
+  while (start <= Math.sqrt(element)) {
+    if (element % start++ < 1) {
+      return false;
+    }
+  }
+  return element > 1;
+}
+
+console.log([4, 6, 8, 12].findIndex(isPrime)); // -1, not found
+console.log([4, 6, 7, 12].findIndex(isPrime)); // 2
+
+ +

폴리필

+ +
if (!Array.prototype.findIndex) {
+  Object.defineProperty(Array.prototype, 'findIndex', {
+    value: function(predicate) {
+      'use strict';
+      if (this == null) {
+        throw new TypeError('Array.prototype.findIndex called on null or undefined');
+      }
+      if (typeof predicate !== 'function') {
+        throw new TypeError('predicate must be a function');
+      }
+      var list = Object(this);
+      var length = list.length >>> 0;
+      var thisArg = arguments[1];
+      var value;
+
+      for (var i = 0; i < length; i++) {
+        value = list[i];
+        if (predicate.call(thisArg, value, i, list)) {
+          return i;
+        }
+      }
+      return -1;
+    },
+    enumerable: false,
+    configurable: false,
+    writable: false
+  });
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-array.prototype.findIndex', 'Array.prototype.findIndex')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.prototype.findIndex', 'Array.prototype.findIndex')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ +
{{Compat("javascript.builtins.Array.findIndex")}}
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/flat/index.html b/files/ko/web/javascript/reference/global_objects/array/flat/index.html new file mode 100644 index 0000000000..4d4af6dc36 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/flat/index.html @@ -0,0 +1,160 @@ +--- +title: Array.prototype.flat() +slug: Web/JavaScript/Reference/Global_Objects/Array/flat +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/flat +--- +
{{JSRef}}
+ +

flat() 메서드는 모든 하위 배열 요소를 지정한 깊이까지 재귀적으로 이어붙인 새로운 배열을 생성합니다.

+ +

구문

+ +
const newArr = arr.flat([depth])
+ +

매개변수

+ +
+
depth {{optional_inline}}
+
중첩 배열 구조를 평탄화할 때 사용할 깊이 값. 기본값은 1입니다.
+
+ +

반환 값

+ +

하위 배열을 이어붙인 새로운 배열.

+ +

예제

+ +

중첩 배열 평탄화

+ +
const arr1 = [1, 2, [3, 4]];
+arr1.flat();
+// [1, 2, 3, 4]
+
+const arr2 = [1, 2, [3, 4, [5, 6]]];
+arr2.flat();
+// [1, 2, 3, 4, [5, 6]]
+
+const arr3 = [1, 2, [3, 4, [5, 6]]];
+arr3.flat(2);
+// [1, 2, 3, 4, 5, 6]
+
+const arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
+arr4.flat(Infinity);
+// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
+ +

배열 구멍 제거

+ +

flat 메서드는 배열의 구멍도 제거합니다.

+ +
const arr5 = [1, 2, , 4, 5];
+arr5.flat();
+// [1, 2, 4, 5]
+ +

대안

+ +

reduce와 concat

+ +
const arr = [1, 2, [3, 4]];
+
+// To flat single level array
+arr.flat();
+// is equivalent to
+arr.reduce((acc, val) => acc.concat(val), []);
+// [1, 2, 3, 4]
+
+// or with decomposition syntax
+const flattened = arr => [].concat(...arr);
+ +

reduce + concat + isArray + 재귀

+ +
const arr = [1, 2, [3, 4, [5, 6]]];
+
+// to enable deep level flatten use recursion with reduce and concat
+function flatDeep(arr, d = 1) {
+   return d > 0 ? arr.reduce((acc, val) => acc.concat(Array.isArray(val) ? flatDeep(val, d - 1) : val), [])
+                : arr.slice();
+};
+
+flatDeep(arr, Infinity);
+// [1, 2, 3, 4, 5, 6]
+ +

스택

+ +
// non recursive flatten deep using a stack
+// note that depth control is hard/inefficient as we will need to tag EACH value with its own depth
+// also possible w/o reversing on shift/unshift, but array OPs on the end tends to be faster
+function flatten(input) {
+  const stack = [...input];
+  const res = [];
+  while(stack.length) {
+    // pop value from stack
+    const next = stack.pop();
+    if(Array.isArray(next)) {
+      // push back array items, won't modify the original input
+      stack.push(...next);
+    } else {
+      res.push(next);
+    }
+  }
+  // reverse to restore input order
+  return res.reverse();
+}
+
+const arr = [1, 2, [3, 4, [5, 6]]];
+flatten(arr);
+// [1, 2, 3, 4, 5, 6]
+ +

Generator 함수

+ +
function* flatten(array, depth) {
+    if(depth === undefined) {
+      depth = 1;
+    }
+    for(const item of array) {
+        if(Array.isArray(item) && depth > 0) {
+          yield* flatten(item, depth - 1);
+        } else {
+          yield item;
+        }
+    }
+}
+
+const arr = [1, 2, [3, 4, [5, 6]]];
+const flattened = [...flatten(arr, Infinity)];
+// [1, 2, 3, 4, 5, 6]
+ +

명세

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-array.prototype.flat', 'Array.prototype.flat')}}
+ +

브라우저 호환성

+ +
+ + +

{{Compat("javascript.builtins.Array.flat")}}

+
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/flatmap/index.html b/files/ko/web/javascript/reference/global_objects/array/flatmap/index.html new file mode 100644 index 0000000000..9d762001e8 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/flatmap/index.html @@ -0,0 +1,148 @@ +--- +title: Array.prototype.flatMap() +slug: Web/JavaScript/Reference/Global_Objects/Array/flatMap +tags: + - Array + - Experimental + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/flatMap +--- +
{{JSRef}} {{SeeCompatTable}}
+ +

flatMap() 메서드는 먼저 매핑함수를 사용해 각 엘리먼트에 대해 map 수행 후, 결과를 새로운 배열로 평탄화합니다. 이는 깊이 1의 flat 이 뒤따르는 map 과 동일하지만, flatMap 은 아주 유용하며 둘을 하나의 메소드로 병합할 때 조금 더 효율적입니다.

+ + + + + +

구문

+ +
arr.flatMap(callback(currentValue[, index[, array]])[, thisArg])
+ +

매개변수

+ +
+
callback
+
새로운 배열의 엘리먼트를 생성하는 함수. 3개의 아규먼트를 갖습니다. +
+
+
currentValue
+
배열에서 처리되는 현재 엘리먼트.
+
index{{optional_inline}}
+
배열에서 처리되고 있는 현재 엘리먼트의 인덱스.
+
array{{optional_inline}}
+
map 이 호출된 배열.
+
+
+
thisArg{{optional_inline}}
+
callback 실행에서 this 로 사용할 값.
+
+ +

반환 값

+ +

각 엘리먼트가 callback 함수의 결과이고, 깊이 1로 평탄화된 새로운 배열.

+ +

설명

+ +

callback 함수의 상세 설명은 {{jsxref("Array.prototype.map()")}} 문서를 보시기 바랍니다. flatMap 메소드는 깊이 1의 flat 이 뒤따르는 map 과 동일합니다.

+ +

예제

+ +

mapflatMap

+ +
let arr1 = [1, 2, 3, 4];
+
+arr1.map(x => [x * 2]);
+// [[2], [4], [6], [8]]
+
+arr1.flatMap(x => [x * 2]);
+// [2, 4, 6, 8]
+
+// 한 레벨만 평탄화됨
+arr1.flatMap(x => [[x * 2]]);
+// [[2], [4], [6], [8]]
+
+ +

위 코드는 map 자체만을 사용해서 구현할 수 있지만, 다음은 flatMap 의 유즈케이스를 더 잘 보여주는 예시입니다.

+ +

문장의 리스트로부터 단어의 리스트를 생성해봅시다.

+ +
let arr1 = ["it's Sunny in", "", "California"];
+
+arr1.map(x=>x.split(" "));
+// [["it's","Sunny","in"],[""],["California"]]
+
+arr1.flatMap(x => x.split(" "));
+// ["it's","Sunny","in","California"]
+ +

출력 리스트의 길이는 입력 리스트의 길이와 다를 수 있습니다.

+ +

flatMap() 을 이용한 아이템 추가 및 제거

+ +

flatMapmap을 하는 과정에서 아이템을 추가하거나 제거하여 아이템 개수를 바꿀 수 있습니다. 다른 말로는 각각의 아이템에 대하여 1:1대응관계 뿐만 아니라 다대다 대응도 가능하다는 것입니다. 이러한 측면에서 filter가 하는 역할의 반대역할을 한다고 볼 수 있습니다. 단순히 아무런 변화를 주고 싶지 않을때에는 원소 하나를 가진 배열을 반환할 수도, 아이템을 추가하고 싶을 때는 다-원소 배열을 반환할 수도, 아이템을 제거하고 싶을 때에는 빈 배열을 반환할 수도 있습니다.

+ +
// 다음은 음수는 제거하고 홀수는 1과 짝수로 분리하는 예시입니다.
+let a = [5, 4, -3, 20, 17, -33, -4, 18]
+//       |\  \  x   |  | \   x   x   |
+//      [4,1, 4,   20, 16, 1,       18]
+
+a.flatMap( (n) =>
+  (n < 0) ?      [] :
+  (n % 2 == 0) ? [n] :
+                 [n-1, 1]
+)
+
+// expected output: [4, 1, 4, 20, 16, 1, 18]
+ +
//=> [1, 2, 3, 4, 5, 6, 7, 8, 9]
+ +

대안

+ +

reduceconcat

+ +
var arr1 = [1, 2, 3, 4];
+
+arr1.flatMap(x => [x * 2]);
+// 다음과 동일합니다
+arr1.reduce((acc, x) => acc.concat([x * 2]), []);
+// [2, 4, 6, 8]
+
+ +
//=> [1, 2, 3, 4, 5, 6, 7, 8, 9]
+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
Array.prototype.flatMap proposalFinished (4)
+ +

브라우저 호환성

+ +
+ + +

{{Compat("javascript.builtins.Array.flatMap")}}

+
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/foreach/index.html b/files/ko/web/javascript/reference/global_objects/array/foreach/index.html new file mode 100644 index 0000000000..809bc4d269 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/foreach/index.html @@ -0,0 +1,264 @@ +--- +title: Array.prototype.forEach() +slug: Web/JavaScript/Reference/Global_Objects/Array/forEach +tags: + - Array + - ECMAScript 5 + - JavaScript + - Method + - Prototype + - Referennce +translation_of: Web/JavaScript/Reference/Global_Objects/Array/forEach +--- +
{{JSRef}}
+ +

forEach() 메서드는 주어진 함수를 배열 요소 각각에 대해 실행합니다.

+ +
{{EmbedInteractiveExample("pages/js/array-foreach.html")}}
+ + + +

구문

+ +
arr.forEach(callback(currentvalue[, index[, array]])[, thisArg])
+ +

매개변수

+ +
+
callback
+
각 요소에 대해 실행할 함수. 다음 세 가지 매개변수를 받습니다.
+
+
+
currentValue
+
처리할 현재 요소.
+
index {{optional_inline}}
+
처리할 현재 요소의 인덱스.
+
array {{optional_inline}}
+
forEach()를 호출한 배열.
+
+
+
thisArg {{optional_inline}}
+
callback을 실행할 때 this로 사용할 값.
+
+ +

반환 값

+ +

{{jsxref("undefined")}}.

+ +

설명

+ +

forEach()는 주어진 callback을 배열에 있는 각 요소에 대해 오름차순으로 한 번씩 실행합니다. 삭제했거나 초기화하지 않은 인덱스 속성에 대해서는 실행하지 않습니다. (예: 희소 배열)

+ +

callback은 다음 세 인수와 함께 호출됩니다.

+ + + +

thisArg 매개변수를 forEach()에 제공한 경우 callback을 호출할 때 전달해 this의 값으로 쓰입니다. 전달하지 않으면 undefined를 사용하며, 최종 this 값은 {{jsxref("Operators/this", "함수의 this를 결정하는 평소 규칙", "", 0)}}을 따릅니다.

+ +

forEach()로 처리할 요소의 범위는 최초 callback 호출 전에 설정됩니다. forEach() 호출을 시작한 뒤 배열에 추가한 요소는 callback이 방문하지 않습니다. 배열의 기존 요소값이 바뀐 경우, callback에 전달하는 값은 forEach()가 요소를 방문한 시점의 값을 사용합니다. 방문하기 전에 삭제한 요소는 방문하지 않습니다.

+ +

forEach()는 각 배열 요소에 대해 한 번씩 callback 함수를 실행합니다. {{jsxref("Array.prototype.map()", "map()")}}과 {{jsxref("Array.prototype.reduce()", "reduce()")}}와는 달리 {{jsxref("undefined")}}를 반환하기 때문에 메서드 체인의 중간에 사용할 수 없습니다. 대표적인 사용처는 메서드 체인 끝에서 부작용side effect을 실행하는 겁니다.

+ +

forEach()는 배열을 변형하지 않습니다. 그러나 callback이 변형할 수는 있습니다.

+ +
+

예외를 던지지 않고는 forEach()를 중간에 멈출 수 없습니다. 중간에 멈춰야 한다면 forEach()가 적절한 방법이 아닐지도 모릅니다.

+ +

다음 방법으로는 조기에 반복을 종료할 수 있습니다.

+ + + +

다른 배열 메서드 {{jsxref("Array.prototype.every()", "every()")}}, {{jsxref("Array.prototype.some()", "some()")}}, {{jsxref("Array.prototype.find()", "find()")}}, {{jsxref("Array.prototype.findIndex()", "findIndex()")}}는 배열 요소를 판별 함수에 전달하고, 그 결과의 참/거짓 여부에 따라 반복의 종료 여부를 결정합니다.

+
+ +

예제

+ +

초기화하지 않은 값의 반복 생략

+ +
const arraySparse = [1,3,,7]
+let numCallbackRuns = 0
+
+arraySparse.forEach(function(element){
+  console.log(element)
+  numCallbackRuns++
+})
+
+console.log("numCallbackRuns: ", numCallbackRuns)
+
+// 1
+// 3
+// 7
+// numCallbackRuns: 3
+// comment: as you can see the missing value between 3 and 7 didn't invoke callback function.
+ +

for 반복문을 forEach()로 바꾸기

+ +
const items = ['item1', 'item2', 'item3'];
+const copy = [];
+
+// 이전
+for (let i=0; i<items.length; i++) {
+  copy.push(items[i]);
+}
+
+// 이후
+items.forEach(function(item){
+  copy.push(item);
+});
+ +

배열 콘텐츠 출력

+ +
+

참고: {{domxref("console.table()")}}을 사용하면 배열 내용물을 서식에 맞춰 출력할 수 있습니다.

+ +

다음 예제는 forEach()를 사용한 다른 방법을 소개합니다.

+
+ +

다음 코드는 배열의 각 요소에 대해 한 줄을 기록합니다:

+ +
function logArrayElements(element, index, array) {
+  console.log('a[' + index + '] = ' + element);
+}
+
+// 인덱스 2는 배열의 그 위치에 항목이 없기에
+// 건너뜀을 주의하세요.
+[2, 5, , 9].forEach(logArrayElements);
+// 기록:
+// a[0] = 2
+// a[1] = 5
+// a[3] = 9
+
+ +

thisArg 사용

+ +

다음 예제는 배열의 각 항목에서 객체의 속성을 갱신합니다:

+ +
function Counter() {
+  this.sum = 0
+  this.count = 0
+}
+Counter.prototype.add = function(array) {
+  array.forEach(function(entry) {
+    this.sum += entry
+    ++this.count
+  }, this)
+  // ^---- 주의
+}
+
+const obj = new Counter()
+obj.add([2, 5, 9])
+obj.count
+// 3
+obj.sum
+// 16
+ +

thisArg 매개변수(this)를 forEach()에 제공했기에, callback은 전달받은 this의 값을 자신의 this 값으로 사용할 수 있습니다. 

+ +
+

화살표 함수 표현식을 사용하여 함수 인수를 전달하는 경우 thisArg 매개변수는 화살표 함수가 {{jsxref("Operators/this", "this")}} 값을 렉시컬(lexical, 정적) 바인딩하기에 생략될 수 있습니다.

+
+ +

객체 복사 함수

+ +

다음 코드는 주어진 객체의 사본을 만듭니다.

+ +

객체 사본을 만드는 방법에는 여러가지가 있습니다, 다음은 그 중 한 방법으로, ECMAScript 5 Object.* 메타 속성 함수를 사용하여 Array.prototype.forEach()가 작동하는 법을 설명하기 위한 코드입니다.

+ +
function copy(obj) {
+  const copy = Object.create(Object.getPrototypeOf(obj))
+  const propNames = Object.getOwnPropertyNames(obj)
+
+  propNames.forEach(function(name) {
+    const desc = Object.getOwnPropertyDescriptor(obj, name)
+    Object.defineProperty(copy, name, desc)
+  })
+
+  return copy
+}
+
+const obj1 = { a: 1, b: 2 }
+const obj2 = copy(obj1)      // obj2 looks like obj1 now
+ +

반복 중 배열이 변경으로 인한 반복 생략

+ +

다음 예제에서는 "one", "two", "four"를 기록합니다.

+ +

forEach()가 값 "two"를 포함하는 항목에 도달하면 전체 배열의 첫 번째 항목을 제거하여, 나머지 모든 항목이 한 위치 앞으로 이동합니다. 요소 "four"는 이제 배열에서 보다 앞에 위치하므로 "three"는 건너 뜁니다.

+ +

forEach()는 반복 전에 배열의 복사본을 만들지 않습니다.

+ +
let words = ['one', 'two', 'three', 'four']
+words.forEach(function(word) {
+  console.log(word)
+  if (word === 'two') {
+    words.shift()
+  }
+})
+// one
+// two
+// four
+ +

배열 평탄화

+ +

다음 예제는 오직 시연 용으로만 추가한 것으로, 평탄화를 하려면 {{jsxref("Array.prototype.flat()")}}을 사용하세요.

+ +
function flatten(arr) {
+  const result = []
+
+  arr.forEach((i) => {
+    if (Array.isArray(i)) {
+      result.push(...flatten(i))
+    } else {
+      result.push(i)
+    }
+  })
+
+  return result
+}
+
+// Usage
+const nested = [1, 2, 3, [4, 5, [6, 7], 8, 9]]
+
+flatten(nested) // [1, 2, 3, 4, 5, 6, 7, 8, 9]
+ +

명세

+ + + + + + + + + + +
명세
{{SpecName('ESDraft', '#sec-array.prototype.foreach', 'Array.prototype.forEach')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Array.forEach")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/from/index.html b/files/ko/web/javascript/reference/global_objects/array/from/index.html new file mode 100644 index 0000000000..487cc36848 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/from/index.html @@ -0,0 +1,244 @@ +--- +title: Array.from() +slug: Web/JavaScript/Reference/Global_Objects/Array/from +tags: + - Array + - ECMAScript 2015 + - JavaScript + - Method + - Reference + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/from +--- +
{{JSRef}}
+ +

Array.from() 메서드는 유사 배열 객체(array-like object)나반복 가능한 객체(iterable object)를 얕게 복사해새로운Array 객체를 만듭니다.

+ +
{{EmbedInteractiveExample("pages/js/array-from.html")}}
+ + + +

구문

+ +
Array.from(arrayLike[, mapFn[, thisArg]])
+
+ +

매개변수

+ +
+
arrayLike
+
배열로 변환하고자 하는유사 배열 객체나 반복 가능한 객체.
+
mapFn{{Optional_inline}}
+
배열의 모든 요소에 대해 호출할 맵핑 함수.
+
thisArg{{Optional_inline}}
+
mapFn 실행 시에 this로 사용할 값.
+
+ +

반환 값

+ +

새로운 {{jsxref("Array")}} 인스턴스.

+ +

설명

+ +

다음과 같은 경우에 Array.from()으로새Array를 만들 수 있습니다.

+ + + +

Array.from()은 선택 매개변수인 mapFn를 가지는데,배열(혹은 배열 서브클래스)의 각 요소를{{jsxref("Array.prototype.map", "맵핑", "", 0)}}할 때 사용할 수 있습니다. 즉,Array.from(obj, mapFn, thisArg)는 중간에 다른 배열을 생성하지 않는다는 점을 제외하면Array.from(obj).map(mapFn, thisArg)와 같습니다. 이 특징은 typed arrays와 같은 특정 배열 서브클래스에서 중간 배열 값이 적절한 유형에 맞게 생략되기 때문에 특히 중요합니다.

+ +

from() 메서드의 length 속성은 1입니다.

+ +

ES2015 이후, 클래스 구문은 내장 및 새 클래스의 상속을 가능케 했습니다. 그 결과로 Array.from과 같은 정적 메서드는 Array의 서브클래스에 의해 상속되며, Array 대신 자신의 인스턴스를 만듭니다.

+ +

예제

+ +

String에서 배열 만들기

+ +
Array.from('foo');
+// ["f", "o", "o"]
+
+ +

Set에서 배열 만들기

+ +
const s = new Set(['foo', window]);
+Array.from(s);
+// ["foo", window]
+
+ +

Map에서 배열 만들기

+ +
const m = new Map([[1, 2], [2, 4], [4, 8]]);
+Array.from(m);
+// [[1, 2], [2, 4], [4, 8]]
+
+const mapper = new Map([['1', 'a'], ['2', 'b']]);
+Array.from(mapper.values());
+// ['a', 'b'];
+
+Array.from(mapper.keys());
+// ['1', '2'];
+
+ +

배열 형태를 가진 객체(arguments)에서 배열 만들기

+ +
function f() {
+  return Array.from(arguments);
+}
+
+f(1, 2, 3);
+
+// [1, 2, 3]
+
+ +

Array.from과 화살표 함수 사용하기

+ +
// Using an arrow function as the map function to
+// manipulate the elements
+Array.from([1, 2, 3], x => x + x);
+// [2, 4, 6]
+
+// Generate a sequence of numbers
+// Since the array is initialized with `undefined` on each position,
+// the value of `v` below will be `undefined`
+Array.from({length: 5}, (v, i) => i);
+// [0, 1, 2, 3, 4]
+
+ +

시퀀스 생성기(range)

+ +
// Sequence generator function (commonly referred to as "range", e.g. Clojure, PHP etc)
+const range = (start, stop, step) => Array.from({ length: (stop - start) / step + 1}, (_, i) => start + (i * step));
+
+// Generate numbers range 0..4
+range(0, 4, 1);
+// [0, 1, 2, 3, 4]
+
+// Generate numbers range 1..10 with step of 2
+range(1, 10, 2);
+// [1, 3, 5, 7, 9]
+
+// Generate the alphabet using Array.from making use of it being ordered as a sequence
+range('A'.charCodeAt(0), 'Z'.charCodeAt(0), 1).map(x => String.fromCharCode(x));
+// ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
+ +

폴리필

+ +

Array.from은 ECMA-262 표준 제6판에 추가됐습니다.따라서 어떤 표준 구현체에서는 사용할 수없을 수도 있습니다. 다른 모든 코드 이전에 아래 코드를 포함하면 지원하지 않는 플랫폼에서도Array.from을사용할 수 있습니다. 아래 알고리즘은ObjectTypeError가 변형되지 않고,callback.call의 계산 값이 원래의Function.prototype.call()과 같은 경우ECMA-262 제6판이 명시한 것과 동일합니다.또한 반복가능자(iterable)는 완벽하게 폴리필할 수없기에 본 구현은 ECMA-262 제6판의 제네릭 반복가능자를 지원하지 않습니다.

+ +
// Production steps of ECMA-262, Edition 6, 22.1.2.1
+if (!Array.from) {
+  Array.from = (function () {
+    var toStr = Object.prototype.toString;
+    var isCallable = function (fn) {
+      return typeof fn === 'function' || toStr.call(fn) === '[object Function]';
+    };
+    var toInteger = function (value) {
+      var number = Number(value);
+      if (isNaN(number)) { return 0; }
+      if (number === 0 || !isFinite(number)) { return number; }
+      return (number > 0 ? 1 : -1) * Math.floor(Math.abs(number));
+    };
+    var maxSafeInteger = Math.pow(2, 53) - 1;
+    var toLength = function (value) {
+      var len = toInteger(value);
+      return Math.min(Math.max(len, 0), maxSafeInteger);
+    };
+
+    // The length property of the from method is 1.
+    return function from(arrayLike/*, mapFn, thisArg */) {
+      // 1. Let C be the this value.
+      var C = this;
+
+      // 2. Let items be ToObject(arrayLike).
+      var items = Object(arrayLike);
+
+      // 3. ReturnIfAbrupt(items).
+      if (arrayLike == null) {
+        throw new TypeError('Array.from requires an array-like object - not null or undefined');
+      }
+
+      // 4. If mapfn is undefined, then let mapping be false.
+      var mapFn = arguments.length > 1 ? arguments[1] : void undefined;
+      var T;
+      if (typeof mapFn !== 'undefined') {
+        // 5. else
+        // 5. a If IsCallable(mapfn) is false, throw a TypeError exception.
+        if (!isCallable(mapFn)) {
+          throw new TypeError('Array.from: when provided, the second argument must be a function');
+        }
+
+        // 5. b. If thisArg was supplied, let T be thisArg; else let T be undefined.
+        if (arguments.length > 2) {
+          T = arguments[2];
+        }
+      }
+
+      // 10. Let lenValue be Get(items, "length").
+      // 11. Let len be ToLength(lenValue).
+      var len = toLength(items.length);
+
+      // 13. If IsConstructor(C) is true, then
+      // 13. a. Let A be the result of calling the [[Construct]] internal method
+      // of C with an argument list containing the single item len.
+      // 14. a. Else, Let A be ArrayCreate(len).
+      var A = isCallable(C) ? Object(new C(len)) : new Array(len);
+
+      // 16. Let k be 0.
+      var k = 0;
+      // 17. Repeat, while k < len… (also steps a - h)
+      var kValue;
+      while (k < len) {
+        kValue = items[k];
+        if (mapFn) {
+          A[k] = typeof T === 'undefined' ? mapFn(kValue, k) : mapFn.call(T, kValue, k);
+        } else {
+          A[k] = kValue;
+        }
+        k += 1;
+      }
+      // 18. Let putStatus be Put(A, "length", len, true).
+      A.length = len;
+      // 20. Return A.
+      return A;
+    };
+  }());
+}
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-array.from', 'Array.from')}}{{Spec2('ES6')}}초기 정의.
{{SpecName('ESDraft', '#sec-array.from', 'Array.from')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Array.from")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/includes/index.html b/files/ko/web/javascript/reference/global_objects/array/includes/index.html new file mode 100644 index 0000000000..a646fd3bb4 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/includes/index.html @@ -0,0 +1,173 @@ +--- +title: Array.prototype.includes() +slug: Web/JavaScript/Reference/Global_Objects/Array/includes +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/includes +--- +
{{JSRef}}
+ +

includes() 메서드는 배열이 특정 요소를 포함하고 있는지 판별합니다.

+ +
{{EmbedInteractiveExample("pages/js/array-includes.html")}}
+ + + +

구문

+ +
arr.includes(valueToFind[, fromIndex])
+
+ +

매개변수

+ +
+
valueToFind
+
탐색할 요소. +
+

참고: 문자나 문자열을 비교할 때, includes()대소문자를 구분합니다.

+
+
+
fromIndex {{optional_inline}}
+
이 배열에서 searchElement 검색을 시작할 위치입니다. 음의 값은 array.length + fromIndex의 인덱스를 asc로 검색합니다. 기본값은 0입니다.
+
+ +

반환 값

+ +

{{jsxref("Boolean")}}.

+ +

예제

+ +
[1, 2, 3].includes(2);     // true
+[1, 2, 3].includes(4);     // false
+[1, 2, 3].includes(3, 3);  // false
+[1, 2, 3].includes(3, -1); // true
+[1, 2, NaN].includes(NaN); // true
+
+ +

fromIndex 가 배열의 길이보다 같거나 큰 경우

+ +

fromIndex 가 배열의 길이보다 같거나 크다면, false 를 반환합니다. 배열은 검색되지 않을 것입니다.

+ +
var arr = ['a', 'b', 'c'];
+
+arr.includes('c', 3);   // false
+arr.includes('c', 100); // false
+ +

0보다 작은 인덱스의 계산

+ +

fromIndex 가 음수라면, 이 계산된 인덱스는 valueToFind 를 찾기 시작할 배열의 위치로 사용되기 위해 연산됩니다. 만약 계산된 인덱스가 -1 * array.length 보다 작거나 같다면, 전체 배열이 검색될 것입니다.

+ +
// array length is 3
+// fromIndex is -100
+// computed index is 3 + (-100) = -97
+
+var arr = ['a', 'b', 'c'];
+
+arr.includes('a', -100); // true
+arr.includes('b', -100); // true
+arr.includes('c', -100); // true
+arr.includes('a', -2); // false
+ +

제네릭 메소드로 사용되는 includes()

+ +

includes() 메서드는 의도적으로 제네릭입니다. 배열 객체가 되기 위한 this 값을 요구하지 않아, 다른 종류의 객체에 적용될 수 있습니다 (e.g. 유사 배열 객체). 아래 예시는  이 함수의 arguments 객체로 호출되는 includes() 메소드를 보여줍니다.

+ +
(function() {
+  console.log([].includes.call(arguments, 'a')); // true
+  console.log([].includes.call(arguments, 'd')); // false
+})('a','b','c');
+ +

폴리필

+ +
// https://tc39.github.io/ecma262/#sec-array.prototype.includes
+if (!Array.prototype.includes) {
+  Object.defineProperty(Array.prototype, 'includes', {
+    value: function(searchElement, fromIndex) {
+
+      if (this == null) {
+        throw new TypeError('"this" is null or not defined');
+      }
+
+      // 1. Let O be ? ToObject(this value).
+      var o = Object(this);
+
+      // 2. Let len be ? ToLength(? Get(O, "length")).
+      var len = o.length >>> 0;
+
+      // 3. If len is 0, return false.
+      if (len === 0) {
+        return false;
+      }
+
+      // 4. Let n be ? ToInteger(fromIndex).
+      //    (If fromIndex is undefined, this step produces the value 0.)
+      var n = fromIndex | 0;
+
+      // 5. If n ≥ 0, then
+      //  a. Let k be n.
+      // 6. Else n < 0,
+      //  a. Let k be len + n.
+      //  b. If k < 0, let k be 0.
+      var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
+
+      function sameValueZero(x, y) {
+        return x === y || (typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y));
+      }
+
+      // 7. Repeat, while k < len
+      while (k < len) {
+        // a. Let elementK be the result of ? Get(O, ! ToString(k)).
+        // b. If SameValueZero(searchElement, elementK) is true, return true.
+        if (sameValueZero(o[k], searchElement)) {
+          return true;
+        }
+        // c. Increase k by 1.
+        k++;
+      }
+
+      // 8. Return false
+      return false;
+    }
+  });
+}
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES7', '#sec-array.prototype.includes', 'Array.prototype.includes')}}{{Spec2('ES7')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.prototype.includes', 'Array.prototype.includes')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ +
{{Compat("javascript.builtins.Array.includes")}}
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/index.html b/files/ko/web/javascript/reference/global_objects/array/index.html new file mode 100644 index 0000000000..4bb18af837 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/index.html @@ -0,0 +1,493 @@ +--- +title: Array +slug: Web/JavaScript/Reference/Global_Objects/Array +tags: + - Array + - Example + - Global Objects + - JavaScript + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array +--- +
{{JSRef}}
+ +

JavaScript Array 전역 객체는 배열을 생성할 때 사용하는 리스트 형태의 고수준 객체입니다.

+ +

설명

+ +

배열은 프로토타입으로 탐색과 변형 작업을 수행하는 메서드를 갖는, 리스트와 비슷한 객체입니다. JavaScript에서 배열의 길이와 요소의 자료형은 고정되어 있지 않습니다. 배열의 길이가 언제든지 늘어나거나 줄어들 수 있기 때문에 JavaScript 배열들은 밀집도가 보장되지 않습니다. 보통 이 성질은 편리하지만, 목적에 맞지 않는다면 형식화 배열(typed array)을 사용하는 것을 고려해보세요.

+ +

배열은 요소 인덱스로 문자열(연관 배열)을 사용할 수 없으며 무조건 정수만 허용합니다. 속성 접근자를 사용해 정수 외 키에 접근할 경우 배열 리스트의 요소가 아니라 배열 객체의 속성 변수를 설정하거나 회수합니다. 배열 객체의 속성과 배열 요소의 리스트의 요소는 서로 다른 별개의 항목으로, 순회 및 변형 작업은 객체 속성에 적용되지 않습니다.

+ +

자주 사용하는 연산

+ +

배열 만들기

+ +
let fruits = ['사과', '바나나']
+
+console.log(fruits.length)
+// 2
+
+ +

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

+ +
let first = fruits[0]
+// 사과
+
+let last = fruits[fruits.length - 1]
+// 바나나
+
+ +

배열의 항목들을 순환하며 처리하기

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

배열 끝에 항목 추가하기

+ +
let newLength = fruits.push('오렌지')
+// ["사과", "바나나", "오렌지"]
+
+ +

배열 끝에서부터 항목 제거하기

+ +
let last = fruits.pop() // 끝에있던 '오렌지'를 제거
+// ["사과", "바나나"]
+
+ +

배열 앞에서부터 항목 제거하기

+ +
let first = fruits.shift() // 제일 앞의 '사과'를 제거
+// ["바나나"]
+
+ +

배열 앞에 항목 추가하기

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

배열 안 항목의 인덱스 찾기

+ +
fruits.push('망고')
+// ["딸기", "바나나", "망고"]
+
+let pos = fruits.indexOf("바나나")
+// 1
+
+ +

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

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

인덱스 위치에서부터 여러개의 항목 제거하기

+ +
let vegetables = ['양배추', '순무', '무', '당근']
+console.log(vegetables)
+// ["양배추", "순무", "무", "당근"]
+
+let pos = 1
+let n = 2
+
+let removedItems = vegetables.splice(pos, n)
+// 배열에서 항목을 제거하는 방법
+// pos 인덱스부터 n개의 항목을 제거함
+
+console.log(vegetables)
+// ["양배추", "당근"] (원 배열 vegetables의 값이 변함)
+
+console.log(removedItems)
+// ["순무", "무"]
+
+ +

배열 복사하기

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

배열 요소에 접근하기

+ +

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

+ +

잘못된 인덱스를 사용하면 undefined를 반환합니다.

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

toString이 속성인 것과 마찬가지로(정확히 하자면, toString()은 메서드입니다) 배열의 요소도 속성입니다. 하지만 아래의 예시처럼 배열 요소에 접근하려 하면, 속성 이름이 유효하지 않기 때문에 구문 오류가 발생합니다.

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

이 점에는 JavaScript 배열과 속성에 특별한 점이 없습니다. 숫자로 시작하는 JavaScript 속성은 마침표 구문으로 접근할 수 없으며, 반드시 괄호 표기법으로 접근해야 합니다.

+ +

예를 들어 '3d'라는 이름의 속성을 가진 객체에서 해당 속성에 접근할 땐 괄호 표기법을 사용해야만 합니다.

+ +
let 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']);
+
+ +

length 와 숫자형 속성의 관계

+ +

JavaScript 배열의 {{jsxref("Array.length", "length")}} 속성과 숫자형 속성은 연결되어 있습니다.

+ +

몇몇 배열 내장 메서드({{jsxref("Array.join", "join")}}, {{jsxref("Array.slice", "slice")}}, {{jsxref("Array.indexOf", "indexOf")}} 등)은 호출했을 때 배열의 {{jsxref("Array.length", "length")}} 속성의 값을 참조합니다.

+ +

다른 메서드({{jsxref("Array.push", "push")}}, {{jsxref("Array.splice", "splice")}} 등) 또한 배열의 {{jsxref("Array.length", "length")}} 속성의 업데이트를 유발합니다.

+ +
const fruits = []
+fruits.push('banana', 'apple', 'peach')
+
+console.log(fruits.length) // 3
+
+ +

JavaScript 배열의 속성을 설정할 때 그 속성이 유효한 배열 인덱스이고 그 인덱스가 현재 배열의 경계를 넘어간다면, JavaScript 엔진은 배열의 {{jsxref("Array.length", "length")}} 속성을 그에 맞춰 업데이트 합니다.

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

{{jsxref("Array.length", "length")}}를 직접 늘릴 수 있습니다.

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

하지만, {{jsxref("Array.length", "length")}} 속성을 감소시키면 요소를 지웁니다.

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

{{jsxref("Array.length")}} 문서에 더 자세한 설명이 있습니다.

+ +

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

+ +

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

+ +
// 하나의 d와 하나 이상의 b에 하나의 d가 뒤따라 일치해야 합니다.
+// 일치한 b와 다음 d를 기억하십시오.
+// 대소문자 구분은 무시됩니다.
+
+var myRe = /d(b+)(d)/i;
+var myArray = myRe.exec('cdbBdbsbz');
+
+ +

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

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
속성/요소설명예시
input {{ReadOnlyInline}}정규 표현식과 일치시키는 원본 문자열을 나타내는 읽기 전용 속성입니다."cdbBdbsbz"
index {{ReadOnlyInline}}원본 문자열에서 정규 표현식이 처음 일치하는 문자열의 위치(원본 문자열의 첫 문자 위치를 0으로 하는)를 나타내는 읽기 전용 속성입니다.1
[0] {{ReadOnlyInline}}원본 문자열에서 정규 표현식이 처음 일치하는 문자열을 지정하는 읽기 전용 요소입니다."dbBd"
[1], ...[n] {{ReadOnlyInline}}만약 정규 표현식에 괄호가 포함돼 있다면 괄호에 일치하는 부분 문자열을 나타내는 읽기 전용 요소들입니다. 가능한 괄호 안의 부분 문자열의 수는 무제한입니다.[1]: bB
+ [2]: d
+ +

생성자

+ +
+
{{jsxref("Array.Array", "Array()")}}
+
Array 객체를 생성합니다.
+
+ +

정적 속성

+ +
+
Array.length
+
값이 1인 Array 생성자의 길이 속성입니다.
+
{{jsxref("Array.@@species", "get Array[@@species]")}}
+
파생 객체를 생성하는데 사용하는 생성자 함수입니다.
+
+ +

정적 메서드

+ +
+
{{jsxref("Array.from()")}}
+
유사 배열 또는 반복 가능한 객체로부터 새로운 Array 인스턴스를 생성합니다.
+
{{jsxref("Array.isArray()")}}
+
만약 변수가 배열이면 참을, 아니면 거짓을 반환합니다.
+
{{jsxref("Array.of()")}}
+
전달인자의 개수나 데이터 타입에 관계없이 새 Array 인스턴스를 생성합니다.
+
+ +

Array 인스턴스

+ +

모든 Array 인스턴스는 Array.prototype을 상속합니다. 다른 생성자와 마찬가지로, Array() 생성자의 프로토타입을 수정하면 모든 Array 인스턴스도 수정의 영향을 받습니다. 예를 들면, 새로운 메서드와 속성을 추가해 모든 Array를 확장할 수 있으므로, {{glossary("polyfill", "폴리필")}}에 쓰입니다.

+ +

그러나 배열 객체에 비표준 메서드를 추가하면 나중에 스스로, 혹은 JavaScript에 기능이 추가될 경우 문제가 될 수 있습니다.

+ +

잘 모를 법한 사실: Array.prototype은 그 스스로 Array입니다.

+ +
Array.isArray(Array.prototype) // true
+ +

인스턴스 속성

+ +
+
+
Array.prototype.constructor
+
객체의 프로토타입을 생성하는 함수를 지정합니다.
+
{{jsxref("Array.prototype.length")}}
+
배열의 원소 수를 나타냅니다.
+
{{jsxref("Array.@@unscopables", "Array.prototype[@@unscopables]")}}
+
{{jsxref("Statements/with", "with")}} 결속 범위로부터 제외하려는 속성 이름이 들어있는 기호입니다.
+
+
+ +

인스턴스 메서드

+ +

변경자 메서드

+ +
+

변경자 메서드는 배열을 수정합니다.

+ +
+
{{jsxref("Array.prototype.copyWithin()")}}
+
배열 내의 지정된 요소들을 동일한 배열 내에서 복사합니다.
+
{{jsxref("Array.prototype.fill()")}}
+
배열 안의 시작 인덱스부터 끝 인덱스까지의 요소값을 지정된 정적 값으로 채웁니다.
+
{{jsxref("Array.prototype.pop()")}}
+
배열에서 마지막 요소를 뽑아내고, 그 요소를 반환합니다.
+
{{jsxref("Array.prototype.push()")}}
+
배열의 끝에 하나 이상의 요소를 추가하고, 변경된 배열의 길이를 반환합니다.
+
{{jsxref("Array.prototype.reverse()")}}
+
배열의 요소 순서를 반전시킵니다. 첫 번째가 마지막이 되고 마지막이 첫 번째가 됩니다.
+
{{jsxref("Array.prototype.shift()")}}
+
배열에서 첫 번째 요소를 삭제하고 그 요소를 반환합니다.
+
{{jsxref("Array.prototype.sort()")}}
+
배열의 요소를 정렬하고 그 배열을 반환합니다.
+
{{jsxref("Array.prototype.splice()")}}
+
배열에서 요소를 추가/삭제합니다.
+
{{jsxref("Array.prototype.unshift()")}}
+
배열의 앞에 하나 이상의 요소를 추가하고 새로운 길이를 반환합니다.
+
+
+ +

접근자 메서드

+ +
+

접근자 메서드는 배열을 수정하지 않고, 기존 배열의 일부에 기반한 새로운 배열 또는 값을 반환합니다.

+ +
+
{{jsxref("Array.prototype.concat()")}}
+
배열을 매개변수로 주어진 배열/값과 이어붙인 새로운 배열을 반환합니다.
+
{{jsxref("Array.prototype.filter()")}}
+
지정한 콜백의 반환 결과가 true인 요소만 모은 새로운 배열을 반환합니다.
+
{{jsxref("Array.prototype.includes()")}}
+
배열이 주어진 값을 포함하는지 판별해 true 또는 false를 반환합니다.
+
{{jsxref("Array.prototype.indexOf()")}}
+
배열에서 주어진 값과 일치하는 제일 앞의 인덱스를 반환합니다. 없으면 -1을 반환합니다.
+
{{jsxref("Array.prototype.join()")}}
+
배열의 모든 요소를 문자열로 합칩니다.
+
{{jsxref("Array.prototype.lastIndexOf()")}}
+
배열에서 주어진 값과 일치하는 제일 뒤의 인덱스를 반환합니다. 없으면 -1을 반환합니다.
+
{{jsxref("Array.prototype.slice()")}}
+
배열의 일부를 추출한 새 배열을 반환합니다.
+
{{jsxref("Array.prototype.toSource()")}} {{non-standard_inline}}
+
지정한 배열을 나타내는 배열 리터럴을 반환합니다. 새로운 배열을 만들기 위해 이 값을 사용할 수 있습니다. {{jsxref("Object.prototype.toSource()")}} 메서드를 재정의합니다.
+
{{jsxref("Array.prototype.toString()")}}
+
배열과 그 요소를 나타내는 문자열을 반환합니다. {{jsxref("Object.prototype.toString()")}} 메서드를 재정의합니다.
+
{{jsxref("Array.prototype.toLocaleString()")}}
+
배열과 그 요소를 나타내는 지역화된 문자열을 반환합니다. {{jsxref("Object.prototype.toLocaleString()")}} 메서드를 재정의합니다.
+
+
+ +

순회 메서드

+ +

배열을 처리하면서 호출할 콜백 함수를 받는 메서드 여럿이 존재합니다. 이런 메서드를 호출하면 배열의 length를 기억하므로, 아직 순회를 끝내지 않았을 때 요소를 더 추가하면 콜백이 방문하지 않습니다.

+ +

요소의 값을 바꾸거나, 요소를 제거하는 등 다른 변경점은 콜백 방문 시점에 따라 최종 값에 영향을 줄 수 있습니다. 비록 이런 동작 방식은 잘 정의되어 있으나, 여러분의 코드를 다른 사람이 읽을 때 헷갈리지 않도록 여기에 의존하면 안됩니다.

+ +

반드시 배열을 변형해야 한다면, 새로운 배열로 복사하세요.

+ +
+
+
{{jsxref("Array.prototype.entries()")}}
+
배열의 각 인덱스에 대한 키/값 쌍을 포함하는 새로운 배열 반복자 객체를 반환합니다.
+
{{jsxref("Array.prototype.every()")}}
+
배열의 모든 요소가 주어진 판별 콜백을 만족할 경우 true를 반환합니다.
+
{{jsxref("Array.prototype.find()")}}
+
주어진 판별 콜백을 만족하는 첫 번째 요소를 반환합니다. 만족하는 요소가 없으면 undefined를 반환합니다.
+
{{jsxref("Array.prototype.findIndex()")}}
+
주어진 판별 콜백을 만족하는 첫 번째 요소의 인덱스를 반환합니다. 만족하는 요소가 없으면 undefined를 반환합니다.
+
{{jsxref("Array.prototype.forEach()")}}
+
배열의 각각의 요소에 대해 콜백을 호출합니다.
+
{{jsxref("Array.prototype.keys()")}}
+
배열의 각 인덱스에 대한 키를 가지는 새로운 배열 반복자 객체를 반환합니다.
+
{{jsxref("Array.prototype.map()")}}
+
배열의 모든 요소 각각에 대하여 주어진 콜백 함수를 호출하고, 그 반환값을 모은 새로운 배열을 반환합니다.
+
{{jsxref("Array.prototype.reduce()")}}
+
주어진 콜백 함수를 가산기와 요소 각각에 대해 왼쪽에서 오른쪽으로 호출하여 하나의 값으로 줄인(reduce) 결과를 반환합니다.
+
{{jsxref("Array.prototype.reduceRight()")}}
+
주어진 콜백 함수를 가산기와 요소 각각에 대해 오른쪽에서 왼쪽으로 호출하여 하나의 값으로 줄인(reduce) 결과를 반환합니다.
+
{{jsxref("Array.prototype.some()")}}
+
배열의 어떤 요소가 주어진 판별 콜백을 만족할 경우 true를 반환합니다.
+
{{jsxref("Array.prototype.values()")}}
+
배열의 각 인덱스에 대한 값을 가지는 새로운 배열 반복자 객체를 반환합니다.
+
{{jsxref("Array.prototype.@@iterator()", "Array.prototype[@@iterator]()")}}
+
배열의 각 인덱스에 대한 값을 가지는 새로운 배열 반복자 객체를 반환합니다.
+
+
+ +

예제

+ +

배열 생성

+ +

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

+ +
let 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)는 빈공간으로 만듭니다.

+ +
let 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
+
+ +

배열을 사용하여 일련의 값을 테이블처럼 표시하기

+ +
const values = []
+for (let x = 0; x < 10; x++){
+ values.push([
+  2 ** x,
+  2 * x ** 2
+ ])
+}
+console.table(values)
+ +

결과는 다음과 같습니다.

+ +
0    1    0
+1    2    2
+2    4    8
+3    8    18
+4    16    32
+5    32    50
+6    64    72
+7    128    98
+8    256    128
+9    512    162
+
+ +

(첫번째 열은 (인덱스))

+ +

명세

+ + + + + + + + + + + + +
SpecificationInitial publication
{{SpecName('ESDraft', '#sec-array-objects', 'Array')}}ECMAScript 1
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Array")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/indexof/index.html b/files/ko/web/javascript/reference/global_objects/array/indexof/index.html new file mode 100644 index 0000000000..9748918d5a --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/indexof/index.html @@ -0,0 +1,196 @@ +--- +title: Array.prototype.indexOf() +slug: Web/JavaScript/Reference/Global_Objects/Array/indexOf +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/indexOf +--- +
{{JSRef}}
+ +

indexOf() 메서드는 배열에서 지정된 요소를 찾을 수 있는 첫 번째 인덱스를 반환하고 존재하지 않으면 -1을 반환합니다.

+ +
+

참고: 문자열은 {{jsxref("String.prototype.indexOf()")}}를 참고하세요.

+
+ +

{{EmbedInteractiveExample("pages/js/array-indexof.html")}}

+ +

구문

+ +
arr.indexOf(searchElement[, fromIndex])
+
+ +

매개변수

+ +
+
searchElement
+
배열에서 찾을 요소입니다.
+
fromIndex {{optional_inline}}
+
검색을 시작할 색인입니다. 인덱스가 배열의 길이보다 크거나 같은 경우 -1이 반환되므로 배열이 검색되지 않습니다. 제공된 색인 값이 음수이면 배열 끝에서부터의 오프셋 값으로 사용됩니다. 참고 : 제공된 색인이 음수이면 배열은 여전히 앞에서 뒤로 검색됩니다. 계산 된 인덱스가 0보다 작 으면 전체 배열이 검색됩니다. 기본값 : 0 (전체 배열 검색).
+
+ +

반환 값

+ +

배열 내의 요소의 최초의 인덱스. 발견되지 않으면 -1.

+ +

설명

+ +

indexOf()는 엄격한 동등성 (=== 또는 triple-equals 연산자에서 사용하는 것과 같은 메서드)을 사용하여 검색 요소를 Array의 요소와 비교합니다.

+ +

예제

+ +

indexOf() 사용하기

+ +

다음 예제에서는 indexOf ()를 사용하여 배열의 값을 찾습니다.

+ +
var array = [2, 9, 9];
+array.indexOf(2);     // 0
+array.indexOf(7);     // -1
+array.indexOf(9, 2);  // 2
+array.indexOf(2, -1); // -1
+array.indexOf(2, -3); // 0
+
+ +

요소의 모든 항목 찾기

+ +
var indices = [];
+var array = ['a', 'b', 'a', 'c', 'a', 'd'];
+var element = 'a';
+var idx = array.indexOf(element);
+while (idx != -1) {
+  indices.push(idx);
+  idx = array.indexOf(element, idx + 1);
+}
+console.log(indices);
+// [0, 2, 4]
+
+ +

요소가 배열에 존재하는지 확인하고 배열을 업데이트

+ +
function updateVegetablesCollection (veggies, veggie) {
+    if (veggies.indexOf(veggie) === -1) {
+        veggies.push(veggie);
+        console.log('새로운 veggies 컬렉션 : ' + veggies);
+    } else if (veggies.indexOf(veggie) > -1) {
+        console.log(veggie + ' 은 이미 veggies 컬렉션에 존재합니다.');
+    }
+}
+
+var veggies = ['potato', 'tomato', 'chillies', 'green-pepper'];
+
+updateVegetablesCollection(veggies, 'spinach');
+// 새로운 veggies 컬렉션 : potato, tomato, chillies, green-pepper, spinach
+updateVegetablesCollection(veggies, 'spinach');
+// spinach 은 이미 veggies 컬렉션에 존재합니다.
+
+ +

폴리필

+ +
// ECMA-262, 제 5 판, 15.4.4.14의 생산 단계
+// 참조 : http://es5.github.io/#x15.4.4.14
+if (!Array.prototype.indexOf) {
+  Array.prototype.indexOf = function(searchElement, fromIndex) {
+
+    var k;
+
+    // 1. 이 값을 인수로 전달하는 ToObject를 호출 한 결과를
+    // o라고합니다.
+    if (this == null) {
+      throw new TypeError('"this" is null or not defined');
+    }
+
+    var o = Object(this);
+
+    // 2. lenValue를 Get 함수를 호출 한 결과로 둡니다.
+     // 인수가 "length"인 o의 내부 메소드.
+     // 3. len을 ToUint32 (lenValue)로 지정합니다.
+    var len = o.length >>> 0;
+
+    // 4. len이 0이면 -1을 반환합니다.
+    if (len === 0) {
+      return -1;
+    }
+
+    // 5.Index에서 인수가 전달 된 경우 n을
+    // ToInteger (fromIndex); 그렇지 않으면 n은 0이됩니다.
+    var n = fromIndex | 0;
+
+    // 6. If n >= len, return -1.
+    if (n >= len) {
+      return -1;
+    }
+
+   // 7. n> = 0 인 경우 k를 n이라고 합니다.
+   // 8. 그렇지 않으면 n <0, k는 len - abs (n)이됩니다.
+   // k가 0보다 작은 경우 k를 0으로 만듭니다.
+    k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
+
+    // 9. k <len 인 동안 반복한다.
+    while (k < len) {
+       // a. Pk를 ToString (k)이라고합시다.
+       // 이것은 in 연산자의 LHS 피연산자에 대해 암시 적입니다.
+       // b. kPresent를 호출 한 결과라고합시다.
+       // Hasproperty 인수에 Pk가있는 o의 내부 메소드.
+       //이 단계는 c와 결합 될 수 있습니다.
+       // c. kPresent가 참이면
+       // i. elementK를 Get을 호출 한 결과로합시다.
+       // ToString (k) 인수를 가진 o의 내부 메쏘드.
+       // ii. 적용한 결과와 동일하게 봅시다.
+       // 엄격한 평등 비교 알고리즘
+       // searchElement 및 elementK.
+       // iii. 동일하면 k를 반환합니다.
+      if (k in o && o[k] === searchElement) {
+        return k;
+      }
+      k++;
+    }
+    return -1;
+  };
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.4.4.14', 'Array.prototype.indexOf')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.6.
{{SpecName('ES6', '#sec-array.prototype.indexof', 'Array.prototype.indexOf')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.indexof', 'Array.prototype.indexOf')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ +
+

{{Compat("javascript.builtins.Array.indexOf")}}

+
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/isarray/index.html b/files/ko/web/javascript/reference/global_objects/array/isarray/index.html new file mode 100644 index 0000000000..0a3a074a3d --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/isarray/index.html @@ -0,0 +1,131 @@ +--- +title: Array.isArray() +slug: Web/JavaScript/Reference/Global_Objects/Array/isArray +tags: + - Array + - ECMAScript 5 + - JavaScript + - Method + - Reference + - polyfill + - 자바스크립트 + - 폴리필 +translation_of: Web/JavaScript/Reference/Global_Objects/Array/isArray +--- +
{{JSRef}}
+ +

Array.isArray() 메서드는 인자가 {{jsxref("Array")}}인지 판별합니다.

+ +
Array.isArray([1, 2, 3]);  // true
+Array.isArray({foo: 123}); // false
+Array.isArray('foobar');   // false
+Array.isArray(undefined);  // false
+
+ +

구문

+ +
Array.isArray(obj)
+ +

매개변수

+ +
+
obj
+
검사할 객체.
+
+ +

반환 값

+ +

객체가 {{jsxref("Array")}}라면 true, 아니라면 false.

+ +

설명

+ +

객체가 {{jsxref("Array")}}라면 true를 반환하고, 아니라면 false를 반환합니다.

+ +

자세한 정보는 “Determining with absolute accuracy whether or not a JavaScript object is an array”(자바스크립트 객체가 배열인지 정확히 판별하는 방법) 문서를 참조하세요.

+ +

예제

+ +
// 모두 true 반환
+Array.isArray([]);
+Array.isArray([1]);
+Array.isArray(new Array());
+Array.isArray(new Array('a', 'b', 'c', 'd'));
+Array.isArray(new Array(3));
+// Array.prototype은 스스로도 배열입니다
+Array.isArray(Array.prototype);
+
+// 모두 false 반환
+Array.isArray();
+Array.isArray({});
+Array.isArray(null);
+Array.isArray(undefined);
+Array.isArray(17);
+Array.isArray('Array');
+Array.isArray(true);
+Array.isArray(false);
+Array.isArray({ __proto__: Array.prototype });
+ +

instanceof vs isArray

+ +

Array 객체를 판별할 때, Array.isArrayiframe을 통해서도 작동하기 때문에 instanceof 보다 적합합니다.

+ +
var iframe = document.createElement('iframe');
+document.body.appendChild(iframe);
+xArray = window.frames[window.frames.length-1].Array;
+var arr = new xArray(1,2,3); // [1,2,3]
+
+// 올바른 Array 판별
+Array.isArray(arr);  // true
+// iframe을 통해서 작동하지 않기 때문에 올바르지 않은 방법
+arr instanceof Array; // false
+
+ +

폴리필

+ +

아래 코드를 실행하면 지원하지 않는 환경에서도 Array.isArray()를 사용할 수 있습니다.

+ +
if (!Array.isArray) {
+  Array.isArray = function(arg) {
+    return Object.prototype.toString.call(arg) === '[object Array]';
+  };
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
명세상태주석
{{SpecName('ES5.1', '#sec-15.4.3.2', 'Array.isArray')}}{{Spec2('ES5.1')}}초안. 자바스크립트 1.8.5 에 구현됨.
{{SpecName('ES6', '#sec-array.isarray', 'Array.isArray')}}{{Spec2('ES6')}} +

 

+
{{SpecName('ESDraft', '#sec-array.isarray', 'Array.isArray')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +
{{Compat("javascript.builtins.Array.isArray")}}
+ +

참고

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/join/index.html b/files/ko/web/javascript/reference/global_objects/array/join/index.html new file mode 100644 index 0000000000..7a78c568ab --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/join/index.html @@ -0,0 +1,91 @@ +--- +title: Array.prototype.join() +slug: Web/JavaScript/Reference/Global_Objects/Array/join +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/join +--- +
{{JSRef}}
+ +

join() 메서드는 배열의 모든 요소를 연결해 하나의 문자열로 만듭니다.

+ +

{{EmbedInteractiveExample("pages/js/array-join.html")}}

+ +

구문

+ +
arr.join([separator])
+ +

매개변수

+ +
+
separator {{optional_inline}}
+
배열의 각 요소를 구분할 문자열을 지정합니다. 이 구분자는 필요한 경우 문자열로 변환됩니다. 생략하면 배열의 요소들이 쉼표로 구분됩니다. separator가 빈 문자열이면 모든 요소들이 사이에 아무 문자도 없이 연결됩니다.
+
+ +

반환 값

+ +

배열의 모든 요소들을 연결한 하나의 문자열을 반환합니다. 만약 arr.length 가 0이라면, 빈 문자열을 반환합니다.

+ +

설명

+ +

모든 배열 요소가 문자열로 변환된 다음 하나의 문자열로 연결됩니다.

+ +
+

요소가 undefined 또는 null이면 빈 문자열로 변환합니다.

+
+ +

예제

+ +

네 가지 다른 방법으로 배열 연결하기

+ +

다음 예제에서는 3개의 요소를 가진 배열 a를 만들고, 기본 구분자, 쉼표와 공백, 더하기 기호, 빈 문자열의 네 가지 구분자를 사용해 배열을 연결합니다.

+ +
var a = ['바람', '비', '불'];
+var myVar1 = a.join();      // myVar1에 '바람,비,불'을 대입
+var myVar2 = a.join(', ');  // myVar2에 '바람, 비, 불'을 대입
+var myVar3 = a.join(' + '); // myVar3에 '바람 + 비 + 불'을 대입
+var myVar4 = a.join('');    // myVar4에 '바람비불'을 대입
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
표준상태비고
{{SpecName('ES1')}}{{Spec2('ES1')}}최초 정의.  JavaScript 1.1에 구현됨.
{{SpecName('ES5.1', '#sec-15.4.4.5', 'Array.prototype.join')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-array.prototype.join', 'Array.prototype.join')}}{{Spec2('ES6')}}
+ +

브라우저 호환성

+ +

{{Compat("javascript.builtins.Array.join")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/keys/index.html b/files/ko/web/javascript/reference/global_objects/array/keys/index.html new file mode 100644 index 0000000000..4afb826a3e --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/keys/index.html @@ -0,0 +1,69 @@ +--- +title: Array.prototype.keys() +slug: Web/JavaScript/Reference/Global_Objects/Array/keys +tags: + - Array + - ECMAScript 2015 + - Iterator + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/keys +--- +
{{JSRef}}
+ +

keys() 메서드는 배열의 각 인덱스를 키 값으로 가지는 새로운 Array Iterator 객체를 반환합니다.

+ +

{{EmbedInteractiveExample("pages/js/array-keys.html")}}

+ +

구문

+ +
arr.keys()
+ +

반환 값

+ +

새로운 {{jsxref("Array")}} 반복기 객체.

+ +

예제

+ +

키 반복기는 빈 인덱스를 무시하지 않음

+ +
var arr = ['a', , 'c'];
+var sparseKeys = Object.keys(arr);
+var denseKeys = [...arr.keys()];
+console.log(sparseKeys); // ['0', '2']
+console.log(denseKeys);  // [0, 1, 2]
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-array.prototype.keys', 'Array.prototype.keys')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.prototype.keys', 'Array.prototype.keys')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

{{Compat("javascript.builtins.Array.keys")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/lastindexof/index.html b/files/ko/web/javascript/reference/global_objects/array/lastindexof/index.html new file mode 100644 index 0000000000..7e1519ae78 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/lastindexof/index.html @@ -0,0 +1,103 @@ +--- +title: Array.prototype.lastIndexOf() +slug: Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf +tags: + - Array + - ECMAScript 5 + - JavaScript + - Method + - Prototype + - Reference + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf +--- +
{{JSRef}}
+ +

lastIndexOf() 메서드는 배열에서 주어진 값을 발견할 수 있는 마지막 인덱스를 반환하고, 요소가 존재하지 않으면 -1을 반환합니다. 배열 탐색은 fromIndex에서 시작하여 뒤로 진행합니다.

+ +
{{EmbedInteractiveExample("pages/js/array-lastindexof.html")}}
+ + + +

구문

+ +
arr.lastIndexOf(searchElement[, fromIndex])
+ +

매개변수

+ +
+
searchElement
+
배열에서 찾을 요소.
+
fromIndex {{optional_inline}}
+
역순으로 검색을 시작할 인덱스. 배열의 길이에서 1을 뺀 값(arr.length - 1)이 기본값이므로 지정하지 않을 경우 전체 배열을 검색합니다. 주어진 값이 배열의 길이 이상이면 전체 배열을 검색합니다. 값이 음수인 경우, 배열의 마지막부터 시작하는 인덱스로 처리합니다. 다만, 음수를 제공하더라도 검색 순서는 뒤에서 앞입니다. 위의 모든 절차를 거친 최종 계산값이 0 미만인 경우, lastIndexOf()는 항상 -1을 반환합니다. 즉, 배열을 탐색하지 않습니다.
+
+ +

반환 값

+ +

주어진 값과 일치하는 마지막 요소의 인덱스, 없으면 -1.

+ +

설명

+ +

lastIndexOf는 일치 연산(=== 연산자와 동일)을 사용해 searchElement와 각 요소를 비교합니다.

+ +

예제

+ +

lastIndexOf 사용하기

+ +

다음 예제에서는 lastIndexOf를 사용하여 배열의 값을 찾습니다.

+ +
var array = [2, 5, 9, 2];
+array.lastIndexOf(2);     // 3
+array.lastIndexOf(7);     // -1
+array.lastIndexOf(2, 3);  // 3
+array.lastIndexOf(2, 2);  // 0
+array.lastIndexOf(2, -2); // 0
+array.lastIndexOf(2, -1); // 3
+
+ +

요소의 모든 항목 찾기

+ +

다음 예제에서는 lastIndexOf를 사용하여 {{jsxref("Array.prototype.push", "push")}}를 사용하여 지정된 배열의 요소 색인을 모두 찾아서 다른 배열에 추가합니다.

+ +
var indices = [];
+var array = ['a', 'b', 'a', 'c', 'a', 'd'];
+var element = 'a';
+var idx = array.lastIndexOf(element);
+while (idx != -1) {
+  indices.push(idx);
+  idx = (idx > 0 ? array.lastIndexOf(element, idx - 1) : -1);
+}
+
+console.log(indices);
+// [4, 2, 0]
+
+ +

배열의 첫 번째 요소 인 경우 요소가 fromIndex 매개 변수와 관계없이 항상 발견되므로 idx == 0 사례를 여기에서 개별적으로 처리해야합니다. 이는 {{jsxref ( "Array.prototype.indexOf", "indexOf")}} 메소드와 다릅니다.

+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-array.prototype.lastindexof', 'Array.prototype.lastIndexOf')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ +

{{Compat("javascript.builtins.Array.lastIndexOf")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/length/index.html b/files/ko/web/javascript/reference/global_objects/array/length/index.html new file mode 100644 index 0000000000..b241e88045 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/length/index.html @@ -0,0 +1,135 @@ +--- +title: Array.length +slug: Web/JavaScript/Reference/Global_Objects/Array/length +tags: + - Array + - JavaScript + - Property + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/length +--- +
{{JSRef}}
+ +

Array 인스턴스의 length 속성은 배열의 길이를 반환합니다. 반환값은 부호 없는 32비트 정수형이며, 배열의 최대 인덱스보다 항상 큽니다. length 속성에 값을 설정할 경우 배열의 길이를 변경합니다.

+ +
{{EmbedInteractiveExample("pages/js/array-length.html")}}
+ + + +

설명

+ +

length 속성의 값은 양의 정수이며 232 미만의 값을 가집니다.

+ +
var namelistA = new Array(4294967296); // 2의 32제곱 = 4294967296
+var namelistC = new Array(-100) // 음수
+
+console.log(namelistA.length); // RangeError: Invalid array length
+console.log(namelistC.length); // RangeError: Invalid array length
+
+var namelistB = [];
+namelistB.length = Math.pow(2,32)-1; // 길이를 2의 32제곱 미만으로 설정
+console.log(namelistB.length);
+
+// 4294967295
+ +

아무 때나 length 속성에 값을 설정해 배열을 절단할 수 있습니다. length 속성으로 배열의 길이를 늘리면 실제 원소의 수가 증가합니다. 예를 들어 길이가 2인 배열의 length를 3으로 설정한다면 마지막에 undefined가 추가돼 총 3개의 요소를 갖게 됩니다.

+ +
var arr = [1, 2, 3];
+printEntries(arr);
+
+arr.length = 5; // set array length to 5 while currently 3.
+printEntries(arr);
+
+function printEntries(arr) {
+  var length = arr.length;
+  for (var i = 0; i < length; i++) {
+    console.log(arr[i]);
+  }
+  console.log('=== printed ===');
+}
+
+// 1
+// 2
+// 3
+// === printed ===
+// 1
+// 2
+// 3
+// undefined
+// undefined
+// === printed ===
+
+ +

그러나 length 속성의 값이 꼭 배열에 정의된 원소의 수를 나타내진 않습니다. length와 숫자형 속성의 관계를 참고하세요.

+ +

{{js_property_attributes(1, 0, 0)}}

+ +

예제

+ +

배열 순회

+ +

다음 예제는 numbers 배열을 length 속성의 크기만큼 순회합니다. 각 원소의 값은 두 배가 됩니다.

+ +
var numbers = [1, 2, 3, 4, 5];
+var length = numbers.length;
+for (var i = 0; i < length; i++) {
+  numbers[i] *= 2;
+}
+// numbers is now [2, 4, 6, 8, 10]
+
+ +

배열 단축

+ +

다음 예제는 numbers 배열의 현재 길이가 3보다 클 경우 3으로 줄입니다.

+ +
var numbers = [1, 2, 3, 4, 5];
+
+if (numbers.length > 3) {
+    numbers.length = 3;
+}
+
+console.log(numbers); // [1, 2, 3]
+console.log(numbers.length); // 3
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.4.5.2', 'Array.length')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-properties-of-array-instances-length', 'Array.length')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-properties-of-array-instances-length', 'Array.length')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +
{{Compat("javascript.builtins.Array.length")}}
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/map/index.html b/files/ko/web/javascript/reference/global_objects/array/map/index.html new file mode 100644 index 0000000000..b3f494a8e3 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/map/index.html @@ -0,0 +1,293 @@ +--- +title: Array.prototype.map() +slug: Web/JavaScript/Reference/Global_Objects/Array/map +tags: + - Array + - ECMAScript 5 + - JavaScript + - Method + - Prototype + - Reference + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/map +--- +
{{JSRef}}
+ +

map() 메서드는 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환합니다.

+ +

{{EmbedInteractiveExample("pages/js/array-map.html")}}

+ +

구문

+ +
arr.map(callback(currentValue[, index[, array]])[, thisArg])
+ +

매개변수

+ +
+
callback
+
새로운 배열 요소를 생성하는 함수. 다음 세 가지 인수를 가집니다.
+
+
+
currentValue
+
처리할 현재 요소.
+
index {{optional_inline}}
+
처리할 현재 요소의 인덱스.
+
array {{optional_inline}}
+
map()을 호출한 배열.
+
+
+
thisArg {{optional_inline}}
+
callback을 실행할 때 this로 사용되는 값.
+
+ +

반환 값

+ +

배열의 각 요소에 대해 실행한 callback의 결과를 모은 새로운 배열.

+ +

설명

+ +

mapcallback 함수를 각각의 요소에 대해 한번씩 순서대로 불러 그 함수의 반환값으로 새로운 배열을 만듭니다. callback 함수는 ({{jsxref("undefined")}}도 포함해서) 배열 값이 들어있는 인덱스에 대해서만 호출됩니다. 즉, 값이 삭제되거나 아직 값이 할당/정의되지 않은 인덱스에 대해서는 호출되지 않습니다.

+ +

callback 함수는 호출될 때 대상 요소의 값, 그 요소의 인덱스, 그리고 map을 호출한 원본 배열 3개의 인수를 전달받습니다.

+ +

thisArg 매개변수가 map에 전달된 경우 callback 함수의 this값으로 사용됩니다. 그 외의 경우 {{jsxref("undefined")}}값이 this 값으로 사용됩니다. callback 함수에서 최종적으로 볼 수 있는 this 값은  함수 내 this를 정하는 일반적인 규칙에 따라 결정됩니다.

+ +

map은 호출한 배열의 값을 변형하지 않습니다. 단, callback 함수에 의해서 변형될 수는 있습니다.

+ +

map이  처리할 요소의 범위는 첫 callback을 호출하기 전에 정해집니다. map이 시작한 이후 배열에 추가되는 요소들은 callback을 호출하지 않습니다. 배열에 존재하는 요소들의 값이 바뀐 경우 map이 방문하는 시점의 값이 callback에 전달됩니다. map이 시작되고, 방문하기 전에 삭제된 요소들은 방문하지 않습니다.

+ +

명세서에 정의된 알고리즘으로 인해 map을 호출한 배열의 중간이 비어있는 경우, 결과 배열 또한 동일한 인덱스를 빈 값으로 유지합니다.

+ +

예제

+ +

배열에 들어있는 숫자들의 제곱근을 구하여 새로운 배열을 만들기

+ +

다음 코드는 숫자의 배열을 받아 각 숫자들의 제곱근이 들어있는 새로운 배열을 만듭니다.

+ +
var numbers = [1, 4, 9];
+var roots = numbers.map(Math.sqrt);
+// roots는 [1, 2, 3]
+// numbers는 그대로 [1, 4, 9]
+
+ +

map을 활용해 배열 속 객체를 재구성하기

+ +

다음 코드는 오브젝트의 배열을 받아 각 오브젝트를 다른 형태으로 재구성해 새로운 배열을 만듭니다.

+ +
var kvArray = [{key:1, value:10},
+               {key:2, value:20},
+               {key:3, value: 30}];
+
+var reformattedArray = kvArray.map(function(obj){
+   var rObj = {};
+   rObj[obj.key] = obj.value;
+   return rObj;
+});
+// reformattedArray는 [{1:10}, {2:20}, {3:30}]
+
+// kvArray는 그대로
+// [{key:1, value:10},
+//  {key:2, value:20},
+//  {key:3, value: 30}]
+
+ +

인자를 받는 함수를 사용하여 숫자 배열 재구성하기

+ +

다음 코드는 인자가 한개인 함수를 이용하여 map이 어떻게 동작하는지 나타냅니다. 인자인 배열과 안의 요소들은 map을 통해 순회하면서 원본 배열로 부터 자동으로 할당됩니다.

+ +
var numbers = [1, 4, 9];
+var doubles = numbers.map(function(num) {
+  return num * 2;
+});
+// doubles는 이제 [2, 8, 18]
+// numbers는 그대로 [1, 4, 9]
+
+ +

map을 포괄적으로 사용하기

+ +

아래 예제는 {{jsxref("Global_Objects/String", "String")}}에 map을 사용해서 각 문자의 ASCII 인코딩 값을 요소로 갖는 배열을 얻는 방법을 보여줍니다.

+ +
var map = Array.prototype.map;
+var a = map.call('Hello World', function(x) { return x.charCodeAt(0); });
+// a는 이제 [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]
+
+ +

map을 포괄적으로 사용하기 (querySelectorAll)

+ +

아래 예제는 querySelectorAll을 사용해서 수집된 객체들을 순회 처리하는 법을 보여줍니다. 이번 경우 체크한 옵션 박스를 콘솔에 프린트합니다.

+ +
var elems = document.querySelectorAll('select option:checked');
+var values = [].map.call(elems, function(obj) {
+  return obj.value;
+});
+
+ +

더 쉬운 방법은 {{jsxref("Array.from()")}}을 사용하는 것입니다.

+ +

까다로운 사례

+ +

(참고한 블로그 포스트)

+ +

map에 하나의 인자(순회하는 원소)만 받는 콜백을 사용하는 경우가 많습니다. 그러나 어떤 함수는 대개 하나의 인자로 호출하지만 두 개 이상의 인자를 사용하는 경우도 있습니다. 이로 인해 어떤 경우 혼란스러울 수도 있습니다.

+ +
// 아래 라인을 보시면...
+['1', '2', '3'].map(parseInt);
+// 결과를 [1, 2, 3] 으로 기대할 수 있습니다.
+// 그러나 실제 결과는 [1, NaN, NaN] 입니다.
+
+// parseInt 함수는 보통 하나의 인자만 사용하지만, 두 개를 받을 수 있습니다.
+// 첫 번째 인자는 변환하고자 하는 표현이고 두 번째는 숫자로 변환할 때 사용할 진법입니다.
+// Array.prototype.map은 콜백에 세 가지 인자를 전달합니다.
+// 배열의 값, 값의 인덱스, 그리고 배열
+// 세 번째 인자는 parseInt가 무시하지만 두 번째 인자는 아닙니다.
+// 따라서 혼란스러운 결과를 도출할 수 있습니다. 자세한 내용은 블로그 포스트를 참고하시길 바랍니다.
+
+function returnInt(element) {
+  return parseInt(element, 10);
+}
+
+['1', '2', '3'].map(returnInt); // [1, 2, 3]
+// 실제 결과가 예상한 대로 배열의 숫자와 같습니다.
+
+// 위와 같지만 더 간단한 화살표 표현식
+['1', '2', '3'].map(str => parseInt(str));
+
+// 더 간단하게 해결할 수 있는 방법
+['1', '2', '3'].map(Number); // [1, 2, 3]
+// 그러나 `parseInt`와 달리 float이나 지수표현도 반환합니다.
+['1.1', '2.2e2', '3e300'].map(Number); // [1.1, 220, 3e+300]
+
+ +

폴리필

+ +

map은 ECMA-262 표준 제5판에 추가됐습니다. 따라서 어떤 표준 구현체에서는 사용할 수 없을 수도 있습니다. 다른 모든 코드 이전에 아래 코드를 포함하면 지원하지 않는 플랫폼에서도 map을 사용할 수 있습니다. 아래 알고리즘은 {{jsxref("Object")}}, {{jsxref("TypeError")}}, {{jsxref("Array")}}가 변형되지 않고, callback.call의 계산 값이 원래의 {{jsxref("Function.prototype.call()")}}과 같은 경우 ECMA-262 제5판이 명시한 것과 동일합니다.

+ +
// Production steps of ECMA-262, Edition 5, 15.4.4.19
+// Reference: http://es5.github.io/#x15.4.4.19
+if (!Array.prototype.map) {
+
+  Array.prototype.map = function(callback, thisArg) {
+
+    var T, A, k;
+
+    if (this == null) {
+      throw new TypeError(' this is null or not defined');
+    }
+
+    // 1. Let O be the result of calling ToObject passing the |this|
+    //    value as the argument.
+    var O = Object(this);
+
+    // 2. Let lenValue be the result of calling the Get internal
+    //    method of O with the argument "length".
+    // 3. Let len be ToUint32(lenValue).
+    var len = O.length >>> 0;
+
+    // 4. If IsCallable(callback) is false, throw a TypeError exception.
+    // See: http://es5.github.com/#x9.11
+    if (typeof callback !== 'function') {
+      throw new TypeError(callback + ' is not a function');
+    }
+
+    // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
+    if (arguments.length > 1) {
+      T = thisArg;
+    }
+
+    // 6. Let A be a new array created as if by the expression new Array(len)
+    //    where Array is the standard built-in constructor with that name and
+    //    len is the value of len.
+    A = new Array(len);
+
+    // 7. Let k be 0
+    k = 0;
+
+    // 8. Repeat, while k < len
+    while (k < len) {
+
+      var kValue, mappedValue;
+
+      // a. Let Pk be ToString(k).
+      //   This is implicit for LHS operands of the in operator
+      // b. Let kPresent be the result of calling the HasProperty internal
+      //    method of O with argument Pk.
+      //   This step can be combined with c
+      // c. If kPresent is true, then
+      if (k in O) {
+
+        // i. Let kValue be the result of calling the Get internal
+        //    method of O with argument Pk.
+        kValue = O[k];
+
+        // ii. Let mappedValue be the result of calling the Call internal
+        //     method of callback with T as the this value and argument
+        //     list containing kValue, k, and O.
+        mappedValue = callback.call(T, kValue, k, O);
+
+        // iii. Call the DefineOwnProperty internal method of A with arguments
+        // Pk, Property Descriptor
+        // { Value: mappedValue,
+        //   Writable: true,
+        //   Enumerable: true,
+        //   Configurable: true },
+        // and false.
+
+        // In browsers that support Object.defineProperty, use the following:
+        // Object.defineProperty(A, k, {
+        //   value: mappedValue,
+        //   writable: true,
+        //   enumerable: true,
+        //   configurable: true
+        // });
+
+        // For best browser support, use the following:
+        A[k] = mappedValue;
+      }
+      // d. Increase k by 1.
+      k++;
+    }
+
+    // 9. return A
+    return A;
+  };
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.4.4.19', 'Array.prototype.map')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.6.
{{SpecName('ES6', '#sec-array.prototype.map', 'Array.prototype.map')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.map', 'Array.prototype.map')}}
+ +

브라우저 호환성

+ +
{{Compat("javascript.builtins.Array.map")}}
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/observe/index.html b/files/ko/web/javascript/reference/global_objects/array/observe/index.html new file mode 100644 index 0000000000..015ae049c5 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/observe/index.html @@ -0,0 +1,87 @@ +--- +title: Array.observe() +slug: Web/JavaScript/Reference/Global_Objects/Array/observe +tags: + - Array + - JavaScript + - Method + - Obsolete +translation_of: Archive/Web/JavaScript/Array.observe +--- +
{{JSRef}} {{obsolete_header}}
+ +

Array.observe() 메서드는 {{jsxref("Object.observe()")}}가 객체를 관찰하는 것과 비슷하게 , 배열의 변화를 비동기 적으로 관찰 하는데 사용 되었습니다. 그것은 발생 순서에 따른 변화의 흐름을 제공합니다. Object.observe()가 accept type list ["add", "update", "delete", "splice"]와 함께 호출되는 것과 같습니다. 하지만 이 API는 더이상 사용되지 않고 브라우저에서 제거 되었습니다. 대신, 더 일반적인 {{jsxref("Proxy")}} 객체를 사용하세요.

+ +

구문

+ +
Array.observe(arr, callback)
+ +

매개변수

+ +
+
arr
+
관찰 할 배열
+
callback
+
이 함수는 변화가 일어날때 마다 다음과 같은 인수와 함께 호출됩니다. +
+
changes
+
변경을 나타내는 각 객체들의 배열입니다. 이 변경 객체들의 프로퍼티 들은: +
    +
  • name: 변경된 프로퍼티의 이름
  • +
  • object: 변경 후 배열
  • +
  • type: 변경 타입을 나타내는 문자. "add", "update", "delete", 또는 "splice" 중 하나.
  • +
  • oldValue: "update" 나 "delete"유형에만 해당합니다. 변경 전 값.
  • +
  • index: "splice"유형에만 해당합니다. 변경이 발생한 인덱스.
  • +
  • removed: "splice"유형에만 해당합니다. 삭제 된 요소들의 배열.
  • +
  • addedCount: "splice"유형에만 해당합니다. 추가 된 요소들의 숫자.
  • +
+
+
+
+
+ +

설명

+ +

콜백 함수는 arr이 변경 될 때마다 호출되며 발생하는 순서대로 모든 변경 사항의 배열로 호출됩니다

+ +
+

Array.prototype.pop() "splice" 변경으로 보고되는 것처럼, 변경은 배열 메서드를 통해 일어납니다. 배열 길이를 변경하지 않는 인덱스 할당 변경은 "update" 변경으로 보고 될 수 있습니다.

+
+ +

예제

+ +

다른 변경 유형 로깅(Logging)

+ +
var arr = ['a', 'b', 'c'];
+
+Array.observe(arr, function(changes) {
+  console.log(changes);
+});
+
+arr[1] = 'B';
+// [{type: 'update', object: <arr>, name: '1', oldValue: 'b'}]
+
+arr[3] = 'd';
+// [{type: 'splice', object: <arr>, index: 3, removed: [], addedCount: 1}]
+
+arr.splice(1, 2, 'beta', 'gamma', 'delta');
+// [{type: 'splice', object: <arr>, index: 1, removed: ['B', 'c'], addedCount: 3}]
+
+ +

명세

+ +

Strawman proposal specification.

+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Array.observe")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/of/index.html b/files/ko/web/javascript/reference/global_objects/array/of/index.html new file mode 100644 index 0000000000..edcd9bddc5 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/of/index.html @@ -0,0 +1,104 @@ +--- +title: Array.of() +slug: Web/JavaScript/Reference/Global_Objects/Array/of +tags: + - Array + - ECMAScript 2015 + - JavaScript + - Method + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/of +--- +
{{JSRef}}
+ +

Array.of() 메서드는 인자의 수나 유형에 관계없이 가변 인자를 갖는 새 Array 인스턴스를 만듭니다.

+ +

Array.of()Array 생성자의 차이는 정수형 인자의 처리 방법에 있습니다. Array.of(7)은 하나의 요소 7을 가진 배열을 생성하지만 Array(7)length 속성이 7인 빈 배열을 생성합니다.

+ +
Array.of(7);       // [7]
+Array.of(1, 2, 3); // [1, 2, 3]
+
+Array(7);          // [ , , , , , , ]
+Array(1, 2, 3);    // [1, 2, 3]
+
+ +

구문

+ +
Array.of(element0[, element1[, ...[, elementN]]])
+ +

매개변수

+ +
+
elementN
+
배열을 생성할 때 사용할 요소.
+
+ +

반환 값

+ +

새로운 {{jsxref("Array")}} 객체.

+ +

설명

+ +

이 함수는 ECMAScript 2015 표준 일부입니다. 자세한 정보는 Array.of, Array.from 제안 사항Array.of 폴리필에서 확인하실 수 있습니다.

+ +

예제

+ +
Array.of(1);         // [1]
+Array.of(1, 2, 3);   // [1, 2, 3]
+Array.of(undefined); // [undefined]
+
+ +

폴리필

+ +

아래 코드를 다른 코드 이전에 포함하면 Array.of를 지원하지 않는 환경에서도 사용할 수 있습니다.

+ +
if (!Array.of) {
+  Array.of = function() {
+    return Array.prototype.slice.call(arguments);
+  };
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-array.of', 'Array.of')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.of', 'Array.of')}}{{Spec2('ESDraft')}} 
+ +

 

+ +

 

+ +

 

+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Array.of")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/pop/index.html b/files/ko/web/javascript/reference/global_objects/array/pop/index.html new file mode 100644 index 0000000000..d02df55262 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/pop/index.html @@ -0,0 +1,91 @@ +--- +title: Array.prototype.pop() +slug: Web/JavaScript/Reference/Global_Objects/Array/pop +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/pop +--- +
{{JSRef}}
+ +

pop() 메서드는 배열에서 마지막 요소를 제거하고 그 요소를 반환합니다.

+ +

{{EmbedInteractiveExample("pages/js/array-pop.html")}}

+ +

구문

+ +
arr.pop()
+ +

반환 값

+ +

배열에서 제거한 요소. 빈 배열의 경우 {{jsxref("undefined")}} 를 반환합니다.

+ +

설명

+ +

pop 메서드는 배열에서 마지막 요소를 제거하여 그 값을 호출자(caller)에게 반환합니다.

+ +

pop은 일부러 일반(generic)입니다; 이 메서드는 배열을 닮은 객체에 {{jsxref("Function.call", "호출", "", 1)}} 또는 {{jsxref("Function.apply", "적용", "", 1)}}될 수 있습니다. 0부터 시작하는 일련의 연속되는 숫자 속성 내 마지막을 반영하는 length 속성을 포함하지 않는 객체는 어떤 의미 있는 방식으로도 행동하지 않을 수 있습니다.

+ +

빈 배열에 pop()을 호출하면, {{jsxref("undefined")}}를 반환합니다.

+ +

예제

+ +

배열의 마지막 요소 제거

+ +

다음 코드는 요소 넷을 포함하는 myFish 배열을 생성하고 그 마지막 요소를 제거합니다.

+ +
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
+
+var popped = myFish.pop();
+
+console.log(myFish); // ['angel', 'clown', 'mandarin' ]
+
+console.log(popped); // 'sturgeon'
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('ES3')}}{{Spec2('ES3')}}초기 정의. JavaScript 1.2에서 구현됨.
{{SpecName('ES5.1', '#sec-15.4.4.6', 'Array.prototype.pop')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.pop', 'Array.prototype.pop')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.pop', 'Array.prototype.pop')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

{{Compat("javascript.builtins.Array.pop")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/push/index.html b/files/ko/web/javascript/reference/global_objects/array/push/index.html new file mode 100644 index 0000000000..73d9c9ad78 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/push/index.html @@ -0,0 +1,113 @@ +--- +title: Array.prototype.push() +slug: Web/JavaScript/Reference/Global_Objects/Array/push +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/push +--- +
{{JSRef}}
+ +

push() 메서드는 배열의 끝에 하나 이상의 요소를 추가하고, 배열의 새로운 길이를 반환합니다.

+ +

{{EmbedInteractiveExample("pages/js/array-push.html")}}

+ +

구문

+ +
arr.push(element1[, ...[, elementN]])
+ +

매개변수

+ +
+
elementN
+
배열의 끝에 추가할 요소.
+
+ +

반환 값

+ +

호출한 배열의 새로운 {{jsxref("Array.length", "length")}} 속성.

+ +

설명

+ +

push 메서드는 배열 끝에 여러 값을 추가합니다.

+ +

push는 의도적으로 제네릭합니다. 배열을 닯은 객체에 {{jsxref("Function.call", "call()")}} 또는 {{jsxref("Function.apply", "apply()")}}로 사용될 수 있다. push 메서드는 주어진 값을 입력하는 것을 어디에 시작할 것인지를 결정하기 위해 length 속성에  의존한다. 만약 length 속성이 숫자로 변환 될 수 없다면 인덱스는 0을 사용한다. length 가 생성되게 될 경우에  길이 값이 존재하지 않을 가능성을 포함한다.  

+ +

String(문자열)이 변경할 수 없는 것처럼 비록 이 명령어의 어플리케이션들이 적합하지 않다고 할지라도 단지 원래 배열 같은 객체는 {{jsxref("Global_Objects/String", "strings", "", 1)}}이다.

+ +

예시

+ +

배열에 엘리먼트를 추가 하기

+ +

다음 코드는 두가지 엘리먼트를 포함하는 스포츠 배열을 생성하고 두개의 엘리먼트를 추가 한다. total 변수는 추가한 배열의 새 길이 값을 포함한다. 

+ +
var sports = ['축구', '야구'];
+var total = sports.push('미식축구', '수영');
+
+console.log(sports); // ['축구', '야구', '미식축구', '수영']
+console.log(total);  // 4
+
+ +

두개의 배열을 합치기

+ +

이 예제는 두번째 배열의 모든 엘리먼트를 push 하기 위해 {{jsxref("Function.apply", "apply()")}}를 사용한다.

+ +

만약 두번째 배열( 아래 예제에서는 moreVegs )이 매우 클 경우, 이 메소드를 사용하지 말아야 한다. 실제로 한 함수가 사용가능한 매개변수의 최대 개수에는 제한이 있기 때문이다. 더 자세한 사항은    {{jsxref("Function.apply", "apply()")}} 에서 찾아볼 수 있다.

+ +
var vegetables = ['설탕당근', '감자'];
+var moreVegs = ['셀러리', '홍당무'];
+
+// 첫번째 배열에 두번째 배열을 합친다.
+// vegetables.push('셀러리', '홍당무'); 하는 것과 동일하다.
+Array.prototype.push.apply(vegetables, moreVegs);
+
+console.log(vegetables); // ['설탕당근', '감자', '셀러리', '홍당무']
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
명세서상태비고
{{SpecName('ES3')}}{{Spec2('ES3')}}초기 정의. JavaScript 1.2에서 구현되었음.
{{SpecName('ES5.1', '#sec-15.4.4.7', 'Array.prototype.push')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.push', 'Array.prototype.push')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.push', 'Array.prototype.push')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

{{Compat("javascript.builtins.Array.push")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/reduce/index.html b/files/ko/web/javascript/reference/global_objects/array/reduce/index.html new file mode 100644 index 0000000000..bd3516865e --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/reduce/index.html @@ -0,0 +1,573 @@ +--- +title: Array.prototype.reduce() +slug: Web/JavaScript/Reference/Global_Objects/Array/Reduce +tags: + - Array + - ECMAScript 5 + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/Reduce +--- +
{{JSRef}}
+ +

reduce() 메서드는 배열의 각 요소에 대해 주어진 리듀서(reducer) 함수를 실행하고, 하나의 결과값을 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/array-reduce.html")}}
+ + + +

리듀서 함수는 네 개의 인자를 가집니다.

+ +
    +
  1. 누산기accumulator (acc)
  2. +
  3. 현재 값 (cur)
  4. +
  5. 현재 인덱스 (idx)
  6. +
  7. 원본 배열 (src)
  8. +
+ +

리듀서 함수의 반환 값은 누산기에 할당되고, 누산기는 순회 중 유지되므로 결국 최종 결과는 하나의 값이 됩니다.

+ +

구문

+ +
arr.reduce(callback[, initialValue])
+ +

매개변수

+ +
+
callback
+
배열의 각 요소에 대해 실행할 함수. 다음 네 가지 인수를 받습니다.
+
+
+
accumulator
+
누산기accmulator는 콜백의 반환값을 누적합니다. 콜백의 이전 반환값 또는, 콜백의 첫 번째 호출이면서 initialValue를 제공한 경우에는 initialValue의 값입니다.
+
currentValue
+
처리할 현재 요소.
+
currentIndex {{optional_inline}}
+
처리할 현재 요소의 인덱스. initialValue를 제공한 경우 0, 아니면 1부터 시작합니다.
+
array {{optional_inline}}
+
reduce()를 호출한 배열.
+
+
+
initialValue {{optional_inline}}
+
callback의 최초 호출에서 첫 번째 인수에 제공하는 값. 초기값을 제공하지 않으면 배열의 첫 번째 요소를 사용합니다. 빈 배열에서 초기값 없이 reduce()를 호출하면 오류가 발생합니다.
+
+ +

반환 값

+ +

누적 계산의 결과 값.

+ +

설명

+ +

reduce()는 빈 요소를 제외하고 배열 내에 존재하는 각 요소에 대해 callback 함수를 한 번씩 실행하는데, 콜백 함수는 다음의 네 인수를 받습니다:

+ + + +

콜백의 최초 호출 때 accumulator와 currentValue는 다음 두 가지 값 중 하나를 가질 수 있습니다. 만약 reduce() 함수 호출에서 initialValue를 제공한 경우, accumulatorinitialValue와 같고 currentValue는 배열의 첫 번째 값과 같습니다. initialValue를 제공하지 않았다면, accumulator는 배열의 첫 번째 값과 같고 currentValue는 두 번째와 같습니다.

+ +
+

참고: initialValue를 제공하지 않으면, reduce()는 인덱스 1부터 시작해 콜백 함수를 실행하고 첫 번째 인덱스는 건너 뜁니다. initialValue를 제공하면 인덱스 0에서 시작합니다.

+
+ +

배열이 비어있는데 initialValue도 제공하지 않으면 {{jsxref("TypeError")}}가 발생합니다. 배열의 요소가 (위치와 관계없이) 하나 뿐이면서 initialValue를 제공되지 않은 경우, 또는 initialValue는 주어졌으나 배열이 빈 경우엔 그 단독 값을 callback 호출 없이 반환합니다.

+ +

다음의 예제처럼 initialValue을 제공하지 않으면 출력 가능한 형식이 세 가지이므로, 보통 초기값을 주는 것이 더 안전합니다.

+ +
var maxCallback = ( acc, cur ) => Math.max( acc.x, cur.x );
+var maxCallback2 = ( max, cur ) => Math.max( max, cur );
+
+// initialValue 없이 reduce()
+[ { x: 22 }, { x: 42 } ].reduce( maxCallback ); // 42
+[ { x: 22 }            ].reduce( maxCallback ); // { x: 22 }
+[                      ].reduce( maxCallback ); // TypeError
+
+// map/reduce로 개선 - 비었거나 더 큰 배열에서도 동작함
+[ { x: 22 }, { x: 42 } ].map( el => el.x )
+                        .reduce( maxCallback2, -Infinity );
+ +

reduce() 작동  방식

+ +

다음의 예제를 생각해 봅시다.

+ +
[0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array) {
+  return accumulator + currentValue;
+});
+
+ +

콜백은 4번 호출됩니다. 각 호출의 인수와 반환값은 다음과 같습니다.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
callbackaccumulatorcurrentValuecurrentIndexarray반환 값
1번째 호출011[0, 1, 2, 3, 4]1
2번째 호출122[0, 1, 2, 3, 4]3
3번째 호출333[0, 1, 2, 3, 4]6
4번째 호출644[0, 1, 2, 3, 4]10
+ +

reduce()가 반환하는 값으로는 마지막 콜백 호출의 반환값(10)을 사용합니다.

+ +

완전한 함수 대신에 {{jsxref("Functions/애로우_펑션", "화살표 함수","",1)}}를 제공할 수도 있습니다. 아래 코드는 위의 코드와 같은 결과를 반환합니다.

+ +
[0, 1, 2, 3, 4].reduce( (prev, curr) => prev + curr );
+
+ +

reduce()의 두 번째 인수로 초기값을 제공하는 경우, 결과는 다음과 같습니다:

+ +
[0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array) {
+  return accumulator + currentValue;
+}, 10);
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
 accumulatorcurrentValuecurrentIndexarray반환값
1번째 호출1000[0, 1, 2, 3, 4]10
2번째 호출1011[0, 1, 2, 3, 4]11
3번째 호출1122[0, 1, 2, 3, 4]13
4번째 호출1333[0, 1, 2, 3, 4]16
5번째 호출1644[0, 1, 2, 3, 4]20
+ +

이 때 reduce()가 결과로 반환하는 값은 20입니다.

+ +

예제

+ +

배열의 모든 값 합산

+ +
var sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) {
+  return accumulator + currentValue;
+}, 0);
+// sum is 6
+
+
+ +

화살표 함수로도 작성할 수 있습니다.

+ +
var total = [ 0, 1, 2, 3 ].reduce(
+  ( accumulator, currentValue ) => accumulator + currentValue,
+  0
+);
+ +

객체 배열에서의 값 합산

+ +

객체로 이루어진 배열에 들어 있는 값을 합산하기 위해서는 반드시 초기값을 주어 각 항목이 여러분의 함수를 거치도록 해야 합니다.

+ +
var initialValue = 0;
+var sum = [{x: 1}, {x:2}, {x:3}].reduce(function (accumulator, currentValue) {
+    return accumulator + currentValue.x;
+},initialValue)
+
+console.log(sum) // logs 6
+
+ +

화살표 함수(arrow function)로도 작성할 수 있습니다: 

+ +
var initialValue = 0;
+var sum = [{x: 1}, {x:2}, {x:3}].reduce(
+    (accumulator, currentValue) => accumulator + currentValue.x
+    ,initialValue
+);
+
+console.log(sum) // logs 6
+ +

중첩 배열 펼치기flatten

+ +
var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
+  function(accumulator, currentValue) {
+    return accumulator.concat(currentValue);
+  },
+  []
+);
+// 펼친 결과: [0, 1, 2, 3, 4, 5]
+
+ +

화살표 함수로도 작성할 수 있습니다:

+ +
var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
+  ( accumulator, currentValue ) => accumulator.concat(currentValue),
+  []
+);
+
+ +

객체 내의 값 인스턴스 개수 세기

+ +
var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];
+
+var countedNames = names.reduce(function (allNames, name) {
+  if (name in allNames) {
+    allNames[name]++;
+  }
+  else {
+    allNames[name] = 1;
+  }
+  return allNames;
+}, {});
+// countedNames is:
+// { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }
+
+ +

속성으로 객체 분류하기

+ +
var people = [
+  { name: 'Alice', age: 21 },
+  { name: 'Max', age: 20 },
+  { name: 'Jane', age: 20 }
+];
+
+function groupBy(objectArray, property) {
+  return objectArray.reduce(function (acc, obj) {
+    var key = obj[property];
+    if (!acc[key]) {
+      acc[key] = [];
+    }
+    acc[key].push(obj);
+    return acc;
+  }, {});
+}
+
+var groupedPeople = groupBy(people, 'age');
+// groupedPeople is:
+// {
+//   20: [
+//     { name: 'Max', age: 20 },
+//     { name: 'Jane', age: 20 }
+//   ],
+//   21: [{ name: 'Alice', age: 21 }]
+// }
+
+ +

확장 연산자와 초기값을 이용하여 객체로 이루어진 배열에 담긴 배열 연결하기

+ +
// friends - an array of objects
+// where object field "books" - list of favorite books
+var friends = [{
+  name: 'Anna',
+  books: ['Bible', 'Harry Potter'],
+  age: 21
+}, {
+  name: 'Bob',
+  books: ['War and peace', 'Romeo and Juliet'],
+  age: 26
+}, {
+  name: 'Alice',
+  books: ['The Lord of the Rings', 'The Shining'],
+  age: 18
+}];
+
+// allbooks - list which will contain all friends' books +
+// additional list contained in initialValue
+var allbooks = friends.reduce(function(accumulator, currentValue) {
+  return [...accumulator, ...currentValue.books];
+}, ['Alphabet']);
+
+// allbooks = [
+//   'Alphabet', 'Bible', 'Harry Potter', 'War and peace',
+//   'Romeo and Juliet', 'The Lord of the Rings',
+//   'The Shining'
+// ]
+
+ +

배열의 중복 항목 제거

+ +
+

참고: {{jsxref("Set")}}과 {{jsxref("Array.from()")}}을 사용할 수 있는 환경이라면, let orderedArray = Array.from(new Set(myArray));를 사용해 중복 요소를 제거할 수도 있습니다.

+
+ +
let arr = [1, 2, 1, 2, 3, 5, 4, 5, 3, 4, 4, 4, 4];
+let result = arr.sort().reduce((accumulator, current) => {
+    const length = accumulator.length
+    if (length === 0 || accumulator[length - 1] !== current) {
+        accumulator.push(current);
+    }
+    return accumulator;
+}, []);
+console.log(result); //[1,2,3,4,5]
+
+ +

프로미스를 순차적으로 실행하기

+ +
/**
+ * Runs promises from array of functions that can return promises
+ * in chained manner
+ *
+ * @param {array} arr - promise arr
+ * @return {Object} promise object
+ */
+function runPromiseInSequence(arr, input) {
+  return arr.reduce(
+    (promiseChain, currentFunction) => promiseChain.then(currentFunction),
+    Promise.resolve(input)
+  );
+}
+
+// promise function 1
+function p1(a) {
+  return new Promise((resolve, reject) => {
+    resolve(a * 5);
+  });
+}
+
+// promise function 2
+function p2(a) {
+  return new Promise((resolve, reject) => {
+    resolve(a * 2);
+  });
+}
+
+// function 3  - will be wrapped in a resolved promise by .then()
+function f3(a) {
+ return a * 3;
+}
+
+// promise function 4
+function p4(a) {
+  return new Promise((resolve, reject) => {
+    resolve(a * 4);
+  });
+}
+
+const promiseArr = [p1, p2, f3, p4];
+runPromiseInSequence(promiseArr, 10)
+  .then(console.log);   // 1200
+
+ +

함수 구성을 위한 파이프 함수

+ +
// Building-blocks to use for composition
+const double = x => x + x;
+const triple = x => 3 * x;
+const quadruple = x => 4 * x;
+
+// Function composition enabling pipe functionality
+const pipe = (...functions) => input => functions.reduce(
+    (acc, fn) => fn(acc),
+    input
+);
+
+// Composed functions for multiplication of specific values
+const multiply6 = pipe(double, triple);
+const multiply9 = pipe(triple, triple);
+const multiply16 = pipe(quadruple, quadruple);
+const multiply24 = pipe(double, triple, quadruple);
+
+// Usage
+multiply6(6); // 36
+multiply9(9); // 81
+multiply16(16); // 256
+multiply24(10); // 240
+
+ +

reduce()로 map() 작성

+ +
if (!Array.prototype.mapUsingReduce) {
+  Array.prototype.mapUsingReduce = function(callback, thisArg) {
+    return this.reduce(function(mappedArray, currentValue, index, array) {
+      mappedArray[index] = callback.call(thisArg, currentValue, index, array);
+      return mappedArray;
+    }, []);
+  };
+}
+
+[1, 2, , 3].mapUsingReduce(
+  (currentValue, index, array) => currentValue + index + array.length
+); // [5, 7, , 10]
+
+
+ +

폴리필

+ +
// ECMA-262의 진행 단계, 5판(Edition), 15.4.4.21
+// 참조: http://es5.github.io/#x15.4.4.21
+// https://tc39.github.io/ecma262/#sec-array.prototype.reduce
+if (!Array.prototype.reduce) {
+  Object.defineProperty(Array.prototype, 'reduce', {
+    value: function(callback /*, initialValue*/) {
+      if (this === null) {
+        throw new TypeError( 'Array.prototype.reduce ' +
+          'called on null or undefined' );
+      }
+      if (typeof callback !== 'function') {
+        throw new TypeError( callback +
+          ' is not a function');
+      }
+
+      // 1. Let O be ? ToObject(this value).
+      var o = Object(this);
+
+      // 2. Let len be ? ToLength(? Get(O, "length")).
+      var len = o.length >>> 0;
+
+      // Steps 3, 4, 5, 6, 7
+      var k = 0;
+      var value;
+
+      if (arguments.length >= 2) {
+        value = arguments[1];
+      } else {
+        while (k < len && !(k in o)) {
+          k++;
+        }
+
+        // 3. If len is 0 and initialValue is not present,
+        //    throw a TypeError exception.
+        if (k >= len) {
+          throw new TypeError( 'Reduce of empty array ' +
+            'with no initial value' );
+        }
+        value = o[k++];
+      }
+
+      // 8. Repeat, while k < len
+      while (k < len) {
+        // a. Let Pk be ! ToString(k).
+        // b. Let kPresent be ? HasProperty(O, Pk).
+        // c. If kPresent is true, then
+        //    i.  Let kValue be ? Get(O, Pk).
+        //    ii. Let accumulator be ? Call(
+        //          callbackfn, undefined,
+        //          « accumulator, kValue, k, O »).
+        if (k in o) {
+          value = callback(value, o[k], k, o);
+        }
+
+        // d. Increase k by 1.
+        k++;
+      }
+
+      // 9. Return accumulator.
+      return value;
+    }
+  });
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.4.4.21', 'Array.prototype.reduce()')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.8.
{{SpecName('ES6', '#sec-array.prototype.reduce', 'Array.prototype.reduce()')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.reduce', 'Array.prototype.reduce()')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +
+ + +

{{Compat("javascript.builtins.Array.reduce")}}

+
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/reduceright/index.html b/files/ko/web/javascript/reference/global_objects/array/reduceright/index.html new file mode 100644 index 0000000000..07bbdb800e --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/reduceright/index.html @@ -0,0 +1,283 @@ +--- +title: Array.prototype.reduceRight() +slug: Web/JavaScript/Reference/Global_Objects/Array/ReduceRight +tags: + - Array + - ECMAScript 5 + - JavaScript + - Method + - Prototype + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/ReduceRight +--- +
{{JSRef}}
+ +

reduceRight() 메서드는 누적기에 대해 함수를 적용하고 배열의 각 값 (오른쪽에서 왼쪽으로)은 값을 단일 값으로 줄여야합니다.

+ +

{{EmbedInteractiveExample("pages/js/array-reduce-right.html")}}

+ +

왼쪽에서 오른쪽으로 {{jsxref("Array.prototype.reduce()")}}도 참조하십시오.

+ +

구문

+ +
arr.reduceRight(callback[, initialValue])
+ +

매개변수

+ +
+
callback
+
4 개의 인수를 취하여 배열의 각 값에 대해 실행할 함수입니다. +
+
previousValue
+
콜백의 마지막 호출에서 이전에 리턴 된 값 또는 제공된 경우 initialValue. (아래 참조).
+
currentValue
+
배열에서 처리중인 현재 요소입니다.
+
index
+
배열에서 처리중인 현재 요소의 인덱스입니다.
+
array
+
배열 reduce가 호출되었습니다.
+
+
+
initialValue
+
선택 과목. 콜백의 최초의 호출의 최초의 인수로서 사용하는 객체입니다.
+
+ +

반환 값

+ +

누적 계산의 결과를 반환합니다.

+ +

설명

+ +

reduceRight는 배열의 구멍을 제외하고 배열에있는 각 요소에 대해 콜백 함수를 한 번 실행합니다.이 인수는 초기 값 (또는 이전 콜백 호출의 값), 현재 요소의 값, 현재 인덱스 및 반복이 일어나는 배열.

+ +

reduceRight 콜백 호출은 다음과 같습니다.

+ +
array.reduceRight(function(previousValue, currentValue, index, array) {
+  // ...
+});
+
+ +

함수가 처음 호출 될 때 previousValue 및 currentValue는 두 값 중 하나가 될 수 있습니다. reduceValue에 대한 호출에 initialValue가 제공된 경우 previousValue는 initialValue와 같고 currentValue는 배열의 마지막 값과 같습니다. initialValue가 제공되지 않으면 previousValue는 배열의 마지막 값과 같고 currentValue는 두 번째 - 마지막 값과 같습니다.

+ +

배열이 비어 있고 initialValue가 제공되지 않으면 {{jsxref ( "TypeError")}}가 발생합니다. 배열에 요소가 1 개만 있어도 (위치에 관계없이) initialValue가 제공되지 않았던 경우, 또는 initialValue가 준비되어 있지만 배열이 비어있는 경우, 콜백을 호출하지 않고 솔로 값이 반환됩니다.

+ +

함수의 일부 실행 예제는 다음과 같습니다.

+ +
[0, 1, 2, 3, 4].reduceRight(function(previousValue, currentValue, index, array) {
+  return previousValue + currentValue;
+});
+
+ +

콜백은 네 번 호출되며 각 호출의 인수와 반환 값은 다음과 같습니다.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
previousValuecurrentValueindexarrayreturn value
first call433[0, 1, 2, 3, 4]7
second call722[0, 1, 2, 3, 4]9
third call911[0, 1, 2, 3, 4]10
fourth call1000[0, 1, 2, 3, 4]10
+ +

reduceRight에 의해 반환 된 값은 마지막 콜백 호출 (10)의 값이됩니다.

+ +

initialValue를 제공하면 결과는 다음과 같습니다.

+ +
[0, 1, 2, 3, 4].reduceRight(function(previousValue, currentValue, index, array) {
+  return previousValue + currentValue;
+}, 10);
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
previousValuecurrentValueindexarrayreturn value
first call1044[0, 1, 2, 3, 4]14
second call1433[0, 1, 2, 3, 4]17
third call1722[0, 1, 2, 3, 4]19
fourth call1911[0, 1, 2, 3, 4]20
fifth call2000[0, 1, 2, 3, 4]20
+ +

reduceRight에 의해 이번에 반환 된 값은 물론 20입니다.

+ +

예제

+ +

배열 내 모든 값의 합계 구하기

+ +
var sum = [0, 1, 2, 3].reduceRight(function(a, b) {
+  return a + b;
+});
+// sum is 6
+
+ +

이중 배열 전개하기

+ +
var flattened = [[0, 1], [2, 3], [4, 5]].reduceRight(function(a, b) {
+    return a.concat(b);
+}, []);
+// flattened is [4, 5, 2, 3, 0, 1]
+
+ +

reduce와 reduceRight의 차이점

+ +
var a = ["1", "2", "3", "4", "5"];
+var left  = a.reduce(function(prev, cur)      { return prev + cur; });
+var right = a.reduceRight(function(prev, cur) { return prev + cur; });
+
+console.log(left);  // "12345"
+console.log(right); // "54321"
+ +

폴리필

+ +

reduceRight는 5 판에서 ECMA-262 표준에 추가되었습니다. 표준의 모든 구현에 존재하지 않을 수도 있습니다. 이 문제를 해결하려면 스크립트 시작 부분에 다음 코드를 삽입하여 reduceRight를 기본적으로 지원하지 않는 구현에서 사용할 수있게하십시오.

+ +
// ECMA-262, 5 판, 15.4.4.22의 제작 단계
+// 참조 : http://es5.github.io/#x15.4.4.22
+if ('function' !== typeof Array.prototype.reduceRight) {
+  Array.prototype.reduceRight = function(callback /*, initialValue*/) {
+    'use strict';
+    if (null === this || 'undefined' === typeof this) {
+      throw new TypeError('Array.prototype.reduce called on null or undefined' );
+    }
+    if ('function' !== typeof callback) {
+      throw new TypeError(callback + ' is not a function');
+    }
+    var t = Object(this), len = t.length >>> 0, k = len - 1, value;
+    if (arguments.length >= 2) {
+      value = arguments[1];
+    } else {
+      while (k >= 0 && !(k in t)) {
+        k--;
+      }
+      if (k < 0) {
+        throw new TypeError('Reduce of empty array with no initial value');
+      }
+      value = t[k--];
+    }
+    for (; k >= 0; k--) {
+      if (k in t) {
+        value = callback(value, t[k], k, t);
+      }
+    }
+    return value;
+  };
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.4.4.22', 'Array.prototype.reduceRight')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.8.
{{SpecName('ES6', '#sec-array.prototype.reduceright', 'Array.prototype.reduceRight')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.reduceright', 'Array.prototype.reduceRight')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +
{{Compat("javascript.builtins.Array.reduceRight")}}
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/reverse/index.html b/files/ko/web/javascript/reference/global_objects/array/reverse/index.html new file mode 100644 index 0000000000..95b4c1a348 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/reverse/index.html @@ -0,0 +1,87 @@ +--- +title: Array.prototype.reverse() +slug: Web/JavaScript/Reference/Global_Objects/Array/reverse +tags: + - Array + - JavaScript + - Method + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Array/reverse +--- +
{{JSRef}}
+ +

reverse() 메서드는 배열의 순서를 반전합니다. 첫 번째 요소는 마지막 요소가 되며 마지막 요소는 첫 번째 요소가 됩니다.

+ +

{{EmbedInteractiveExample("pages/js/array-reverse.html")}}

+ +

구문

+ +
a.reverse()
+ +

반환 값

+ +

순서가 반전된 배열.

+ +

설명

+ +

reverse 메서드는 호출한 배열을 반전하고 원본 배열을 변형하며 그 참조를 반환합니다.

+ +

예시

+ +

배열의 요소를 반전하기

+ +

다음 예시는 3개의 요소가 든 myArray 배열을 만든 후, 반전시킵니다.

+ +
const a = [1, 2, 3];
+console.log(a); // [1, 2, 3]
+
+a.reverse();
+console.log(a); // [3, 2, 1]
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.4.4.8', 'Array.prototype.reverse')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.reverse', 'Array.prototype.reverse')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.reverse', 'Array.prototype.reverse')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +
{{Compat("javascript.builtins.Array.reverse")}}
+ +
 
+ +
 
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/shift/index.html b/files/ko/web/javascript/reference/global_objects/array/shift/index.html new file mode 100644 index 0000000000..bf610b95f9 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/shift/index.html @@ -0,0 +1,102 @@ +--- +title: Array.prototype.shift() +slug: Web/JavaScript/Reference/Global_Objects/Array/shift +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/shift +--- +
{{JSRef}}
+ +

shift() 메서드는 배열에서 첫 번째 요소를 제거하고, 제거된 요소를 반환합니다. 이 메서드는 배열의 길이를 변하게 합니다.

+ +

{{EmbedInteractiveExample("pages/js/array-shift.html")}}

+ +

구문

+ +
arr.shift()
+
+ +

반환 값

+ +

배열에서 제거한 요소. 빈 배열의 경우 {{jsxref("undefined")}} 를 반환합니다.

+ +

설명

+ +

shift 메서드는 0번째 위치의 요소를 제거 하고 연이은 나머지 값들의 위치를 한칸 씩 앞으로 당깁니다. 그리고 제거된 값을 반환 합니다. 만약 배열의 {{jsxref("Array.length", "length")}}가 0이라면 {{jsxref("undefined")}}를 리턴 합니다.

+ +

shift는 의도적인 일반형태로써; 이 메서드는 배열과 유사한 형태의 객체에서  {{jsxref("Function.call", "호출", "", 1)}} 하거나 {{jsxref("Function.apply", "적용", "", 1)}} 할 수 있습니다. 연속된 일련의 마지막 항목을 나타내는 길이 속성을 가지고 있지 않은 객체의 제로베이스 수치 속성에는 의미 있는 작동을 하지 않을 수 있습니다. (Objects which do not contain a length property reflecting the last in a series of consecutive, zero-based numerical properties may not behave in any meaningful manner.)

+ +

예제

+ +

배열에서 한 요소 제거하기

+ +

아래 코드는 myFish 라는 배열에서 첫번째 요소를 제거 하기 전과 후를 보여 줍니다.  그리고 제거된 요소도 보여줍니다.

+ +
var myFish = ['angel', 'clown', 'mandarin', 'surgeon'];
+
+console.log('myFish before: ' + myFish);
+// "제거전 myFish 배열: angel,clown,mandarin,surgeon"
+
+var shifted = myFish.shift();
+
+console.log('myFish after: ' + myFish);
+// "제거후 myFish 배열: clown,mandarin,surgeon"
+
+console.log('Removed this element: ' + shifted);
+// "제거된 배열 요소: angel"
+
+ +

while 반복문 안에서 shift() 사용하기

+ +

shift() 메서드는 while 문의 조건으로 사용되기도 합니다. 아래 코드에서는 while 문을 한번 돌 때 마다 배열의 다음 요소를 제거하고, 이는 빈 배열이 될 때까지 반복됩니다.

+ +
var names = ["Andrew", "Edward", "Paul", "Chris" ,"John"];
+
+while( (i = names.shift()) !== undefined ) {
+    console.log(i);
+}
+// Andrew, Edward, Paul, Chris, John
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.9', 'Array.prototype.shift')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.shift', 'Array.prototype.shift')}}{{Spec2('ES6')}} 
+ +

브라우저 호환성

+ +

{{Compat("javascript.builtins.Array.shift")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/slice/index.html b/files/ko/web/javascript/reference/global_objects/array/slice/index.html new file mode 100644 index 0000000000..a5264b1f86 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/slice/index.html @@ -0,0 +1,155 @@ +--- +title: Array.prototype.slice() +slug: Web/JavaScript/Reference/Global_Objects/Array/slice +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/slice +--- +
{{JSRef}}
+ +

slice() 메서드는 어떤 배열의 begin부터 end까지(end 미포함)에 대한 얕은 복사본을 새로운 배열 객체로 반환합니다. 원본 배열은 바뀌지 않습니다.

+ +
{{EmbedInteractiveExample("pages/js/array-slice.html")}}
+ + + +

구문

+ +
arr.slice([begin[, end]])
+
+ +

매개변수

+ +
+
begin {{optional_inline}}
+
0을 시작으로 하는 추출 시작점에 대한 인덱스를 의미합니다.
+
음수 인덱스는 배열의 끝에서부터의 길이를 나타냅니다. slice(-2) 는 배열에서 마지막 두 개의 엘리먼트를 추출합니다.
+
beginundefined인 경우에는, 0번 인덱스부터 slice 합니다.
+
begin이 배열의 길이보다 큰 경우에는, 빈 배열을 반환합니다.
+
end {{optional_inline}}
+
추출을 종료 할 0 기준 인덱스입니다. sliceend 인덱스를 제외하고 추출합니다.
+
예를 들어, slice(1,4)는 두번째 요소부터 네번째 요소까지 (1, 2 및 3을 인덱스로 하는 요소) 추출합니다.
+
음수 인덱스는 배열의 끝에서부터의 길이를 나타냅니다. 예를들어 slice(2,-1) 는 세번째부터 끝에서 두번째 요소까지 추출합니다.
+
end가 생략되면 slice()는 배열의 끝까지(arr.length) 추출합니다.
+
+ +

     만약 end 값이 배열의 길이보다 크다면, silce()는 배열의 끝까지(arr.length) 추출합니다.

+ +
+
+

반환 값

+
+
+ +

추출한 요소를 포함한 새로운 배열.

+ +

설명

+ +

slice()는 원본을 대체하지 않습니다. 원본 배열에서 요소의 얕은 복사본을 반환합니다. 원본 배열의 요소는 다음과 같이 반환 된 배열에 복사됩니다:

+ + + +

새 요소를 두 배열 중 하나에 추가해도 다른 배열은 영향을 받지 않습니다.

+ +

예제

+ +

기존 배열의 일부 반환

+ +
let fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
+let citrus = fruits.slice(1, 3)
+
+// fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
+// citrus contains ['Orange','Lemon']
+ +

slice 사용하기

+ +

다음 예제에서 slice()myCar에서 newCar라는 새 배열을 만듭니다. 두 가지 모두 myHonda 객체에 대한 참조를 포함합니다. myHonda의 색상이 자주색으로 변경되면 두 배열 모두 변경 사항을 반영합니다.

+ +
// Using slice, create newCar from myCar.
+let myHonda = { color: 'red', wheels: 4, engine: { cylinders: 4, size: 2.2 } }
+let myCar = [myHonda, 2, 'cherry condition', 'purchased 1997']
+let newCar = myCar.slice(0, 2)
+
+// Display the values of myCar, newCar, and the color of myHonda
+//  referenced from both arrays.
+console.log('myCar = ' + JSON.stringify(myCar))
+console.log('newCar = ' + JSON.stringify(newCar))
+console.log('myCar[0].color = ' + myCar[0].color)
+console.log('newCar[0].color = ' + newCar[0].color)
+
+// Change the color of myHonda.
+myHonda.color = 'purple'
+console.log('The new color of my Honda is ' + myHonda.color)
+
+// Display the color of myHonda referenced from both arrays.
+console.log('myCar[0].color = ' + myCar[0].color)
+console.log('newCar[0].color = ' + newCar[0].color)
+ +

스크립트를 실행하면 다음과 같은 기록을 남깁니다.

+ +
myCar = [{color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}, 2,
+         'cherry condition', 'purchased 1997']
+newCar = [{color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}, 2]
+myCar[0].color = red
+newCar[0].color = red
+The new color of my Honda is purple
+myCar[0].color = purple
+newCar[0].color = purple
+ +

배열형 객체

+ +

slice() 메서드를 호출하여 배열형 객체와 콜렉션을 새로운 Array로 변환할 수 있습니다. 단순히 {{jsxref("Function.prototype.bind()")}}를 사용해 객체에 slice()를 바인딩 하면 됩니다. 대표적인 "배열형 객체"의 예시는 함수 내의 {{jsxref("Functions/arguments", "arguments")}}입니다.

+ +
function list() {
+  return Array.prototype.slice.call(arguments);
+}
+
+let list1 = list(1, 2, 3); // [1, 2, 3]
+
+ +

{{jsxref("Function.prototype.call()")}} 메서드를 사용해서도 바인딩을 할 수 있으며, Array.prototype.slice.call 대신 더 짧게 [].slice.call로 작성할 수도 있습니다.

+ +

아무튼, 다음과 같이 {{jsxref("Function.prototype.bind", "bind()")}}를 사용해 줄일 수 있습니다.

+ +
let unboundSlice = Array.prototype.slice
+let slice = Function.prototype.call.bind(unboundSlice)
+
+function list() {
+  return slice(arguments)
+}
+
+let list1 = list(1, 2, 3) // [1, 2, 3]
+ +

명세

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-array.prototype.slice', 'Array.prototype.slice')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Array.slice")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/some/index.html b/files/ko/web/javascript/reference/global_objects/array/some/index.html new file mode 100644 index 0000000000..8fbe19bcda --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/some/index.html @@ -0,0 +1,202 @@ +--- +title: Array.prototype.some() +slug: Web/JavaScript/Reference/Global_Objects/Array/some +tags: + - Array + - ECMAScript 5 + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/some +--- +
{{JSRef}}
+ +

some() 메서드는 배열 안의 어떤 요소라도 주어진 판별 함수를 통과하는지 테스트합니다.

+ +
+

참고: 빈 배열에서 호출하면 무조건 false를 반환합니다.

+
+ +

{{EmbedInteractiveExample("pages/js/array-some.html")}}

+ +

구문

+ +
arr.some(callback[, thisArg])
+ +

매개변수

+ +
+
callback
+
각 요소를 시험할 함수. 다음 세 가지 인수를 받습니다. +
+
currentValue
+
처리할 현재 요소.
+
index {{Optional_inline}}
+
처리할 현재 요소의 인덱스.
+
array {{Optional_inline}}
+
some을 호출한 배열.
+
+
+
thisArg {{Optional_inline}}
+
callback을 실행할 때 this로 사용하는 값.
+
+ +

반환 값

+ +

callback이 어떤 배열 요소라도 대해 참인({{Glossary("truthy")}}) 값을 반환하는 경우 true, 그 외엔 false.

+ +

설명

+ +

somecallback이 참(불린으로 변환했을 때 true가 되는 값)을 반환하는 요소를 찾을 때까지 배열에 있는 각 요소에 대해 한 번씩 callback 함수를 실행합니다. 해당하는 요소를 발견한 경우 some은 즉시 true를 반환합니다. 그렇지 않으면, 즉 모든 값에서 거짓을 반환하면 false를 반환합니다. 할당한 값이 있는 배열의 인덱스에서만 callback을 호출합니다. 삭제했거나 값을 할당한 적이 없는 인덱스에서는 호출하지 않습니다.

+ +

callback은 요소의 값, 해당 요소의 인덱스 및 순회하고 있는 배열 세 가지 인수와 함께 호출됩니다.

+ +

thisArg 매개변수를 some에 제공한 경우 callback의 this로 사용됩니다. 그 외엔 {{jsxref("undefined")}}값을 사용합니다. 최종적으로 callback이 볼 수 있는 this의 값은 함수가 볼 수 있는 this를 결정하는 평소 규칙을 따릅니다.

+ +

some은 호출한 배열을 변형하지 않습니다.

+ +

some이 처리하는 요소의 범위는 callback의 첫 호출 전에 설정됩니다. some 호출 이후로 배열에 추가하는 요소는 callback이 방문하지 않습니다. 배열에 원래 있었지만 아직 방문하지 않은 요소가 callback에 의해 변경된 경우, 그 인덱스를 방문하는 시점의 값을 사용합니다. 삭제한 요소는 방문하지 않습니다.

+ +

예제

+ +

배열의 요소 테스트

+ +

다음 예제는 배열 내 요소 중 하나라도 10보다 큰지 판별합니다.

+ +
function isBiggerThan10(element, index, array) {
+  return element > 10;
+}
+[2, 5, 8, 1, 4].some(isBiggerThan10);  // false
+[12, 5, 8, 1, 4].some(isBiggerThan10); // true
+
+ +

화살표 함수를 사용한 배열의 요소 테스트

+ +

화살표 함수는 같은 테스트에 대해 더 짧은 구문을 제공합니다.

+ +
[2, 5, 8, 1, 4].some(elem => elem > 10);  // false
+[12, 5, 8, 1, 4].some(elem => elem > 10); // true
+
+ +

값이 배열 내 존재하는지 확인

+ +

다음 예제는 요소가 하나라도 배열 내 존재하는 경우 true를 반환합니다.

+ +
var fruits = ['apple', 'banana', 'mango', 'guava'];
+
+function checkAvailability(arr, val) {
+    return arr.some(function(arrVal) {
+        return val === arrVal;
+    });
+}
+
+checkAvailability(fruits, 'kela'); //false
+checkAvailability(fruits, 'banana'); //true
+ +

화살표 함수를 사용하여 값이 존재하는지 확인

+ +
var fruits = ['apple', 'banana', 'mango', 'guava'];
+
+function checkAvailability(arr, val) {
+    return arr.some(arrVal => val === arrVal);
+}
+
+checkAvailability(fruits, 'kela'); //false
+checkAvailability(fruits, 'banana'); //true
+ +

모든 값을 불린으로 변환

+ +
var TRUTHY_VALUES = [true, 'true', 1];
+
+function getBoolean(a) {
+    'use strict';
+
+    var value = a;
+
+    if (typeof value === 'string') {
+        value = value.toLowerCase().trim();
+    }
+
+    return TRUTHY_VALUES.some(function(t) {
+        return t === value;
+    });
+}
+
+getBoolean(false); // false
+getBoolean('false'); // false
+getBoolean(1); // true
+getBoolean('true'); // true
+ +

폴리필

+ +

some은 ECMA-262 표준 제5판에 추가됐습니다. 따라서 어떤 표준 구현체에서는 사용할 수 없을 수도 있습니다. 다른 모든 코드 이전에 아래 코드를 포함하면 지원하지 않는 환경에서도 some을 사용할 수 있습니다. 아래 알고리즘은 {{jsxref("Object")}}와 {{jsxref("TypeError")}}가 변형되지 않고, fun.call의 계산 값이 원래의 {{jsxref("Function.prototype.call()")}}과 같은 경우 ECMA-262 제5판이 명시한 것과 동일합니다.

+ +
// ECMA-262 5판, 15.4.4.17항의 작성 과정
+// 출처: http://es5.github.io/#x15.4.4.17
+if (!Array.prototype.some) {
+  Array.prototype.some = function(fun/*, thisArg*/) {
+    'use strict';
+
+    if (this == null) {
+      throw new TypeError('Array.prototype.some called on null or undefined');
+    }
+
+    if (typeof fun !== 'function') {
+      throw new TypeError();
+    }
+
+    var t = Object(this);
+    var len = t.length >>> 0;
+
+    var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
+    for (var i = 0; i < len; i++) {
+      if (i in t && fun.call(thisArg, t[i], i, t)) {
+        return true;
+      }
+    }
+
+    return false;
+  };
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('ES5.1', '#sec-15.4.4.17', 'Array.prototype.some')}}{{Spec2('ES5.1')}}초기 정의. JavaScript 1.6에서 구현됨.
{{SpecName('ES6', '#sec-array.prototype.some', 'Array.prototype.some')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.some', 'Array.prototype.some')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

{{Compat("javascript.builtins.Array.some")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/sort/index.html b/files/ko/web/javascript/reference/global_objects/array/sort/index.html new file mode 100644 index 0000000000..ddab9a428f --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/sort/index.html @@ -0,0 +1,245 @@ +--- +title: Array.prototype.sort() +slug: Web/JavaScript/Reference/Global_Objects/Array/sort +tags: + - Array + - JavaScript + - Method + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Array/sort +--- +
{{JSRef}}
+ +

sort() 메서드는 배열의 요소를 적절한 위치에 정렬한 후 그 배열을 반환합니다. 정렬은 stable sort가 아닐 수 있습니다. 기본 정렬 순서는 문자열의 유니코드 코드 포인트를 따릅니다.

+ +

정렬 속도와 복잡도는 각 구현방식에 따라 다를 수 있습니다.

+ +

{{EmbedInteractiveExample("pages/js/array-sort.html")}}

+ +

구문

+ +
arr.sort([compareFunction])
+
+ +

매개변수

+ +
+
compareFunction {{optional_inline}}
+
정렬 순서를 정의하는 함수. 생략하면 배열은 각 요소의 문자열 변환에 따라 각 문자의 유니 코드 코드 포인트 값에 따라 정렬됩니다.
+
+ +

반환 값

+ +

정렬한 배열. 원 배열이 정렬되는 것에 유의하세요. 복사본이 만들어지는 것이 아닙니다.

+ +

설명

+ +

compareFunction이 제공되지 않으면 요소를 문자열로 변환하고 유니 코드 코드 포인트 순서로 문자열을 비교하여 정렬됩니다. 예를 들어 "바나나"는 "체리"앞에옵니다. 숫자 정렬에서는 9가 80보다 앞에 오지만 숫자는 문자열로 변환되기 때문에 "80"은 유니 코드 순서에서 "9"앞에옵니다.

+ +

compareFunction이 제공되면 배열 요소는 compare 함수의 반환 값에 따라 정렬됩니다. a와 b가 비교되는 두 요소라면,

+ + + +

따라서 compare 함수의 형식은 다음과 같습니다.

+ +
function compare(a, b) {
+  if (a is less than b by some ordering criterion) {
+    return -1;
+  }
+  if (a is greater than b by the ordering criterion) {
+    return 1;
+  }
+  // a must be equal to b
+  return 0;
+}
+
+ +

문자열 대신 숫자를 비교하기 위해 compare 함수는 a에서 b를 뺄 수 있습니다. 다음 함수는 배열을 오름차순으로 정렬합니다 (Infinity 및 NaN이 포함되어 있지 않은 경우).

+ +
function compareNumbers(a, b) {
+  return a - b;
+}
+
+ +

sort 메소드는 {{jsxref ( "연산자 / 함수", "함수식", "", 1)}} (및 클로저)와 함께 편리하게 사용할 수 있습니다.

+ +
var numbers = [4, 2, 5, 1, 3];
+numbers.sort(function(a, b) {
+  return a - b;
+});
+console.log(numbers);
+
+// [1, 2, 3, 4, 5]
+
+ +

개체는 해당 속성 중 하나의 값을 기준으로 정렬 할 수 있습니다.

+ +
var items = [
+  { name: 'Edward', value: 21 },
+  { name: 'Sharpe', value: 37 },
+  { name: 'And', value: 45 },
+  { name: 'The', value: -12 },
+  { name: 'Magnetic', value: 13 },
+  { name: 'Zeros', value: 37 }
+];
+
+// value 기준으로 정렬
+items.sort(function (a, b) {
+  if (a.value > b.value) {
+    return 1;
+  }
+  if (a.value < b.value) {
+    return -1;
+  }
+  // a must be equal to b
+  return 0;
+});
+
+// name 기준으로 정렬
+items.sort(function(a, b) {
+  var nameA = a.name.toUpperCase(); // ignore upper and lowercase
+  var nameB = b.name.toUpperCase(); // ignore upper and lowercase
+  if (nameA < nameB) {
+    return -1;
+  }
+  if (nameA > nameB) {
+    return 1;
+  }
+
+  // 이름이 같을 경우
+  return 0;
+});
+ +

예제

+ +

배열 만들기, 표시 및 정렬

+ +

다음 예제에서는 네 개의 배열을 만들고 원래 배열을 표시 한 다음 정렬 된 배열을 표시합니다. 숫자 배열은 비교 함수없이 정렬 된 다음 비교 함수로 정렬됩니다.

+ +
var stringArray = ['Blue', 'Humpback', 'Beluga'];
+var numericStringArray = ['80', '9', '700'];
+var numberArray = [40, 1, 5, 200];
+var mixedNumericArray = ['80', '9', '700', 40, 1, 5, 200];
+
+function compareNumbers(a, b) {
+  return a - b;
+}
+
+console.log('stringArray:', stringArray.join());
+console.log('Sorted:', stringArray.sort());
+
+console.log('numberArray:', numberArray.join());
+console.log('Sorted without a compare function:', numberArray.sort());
+console.log('Sorted with compareNumbers:', numberArray.sort(compareNumbers));
+
+console.log('numericStringArray:', numericStringArray.join());
+console.log('Sorted without a compare function:', numericStringArray.sort());
+console.log('Sorted with compareNumbers:', numericStringArray.sort(compareNumbers));
+
+console.log('mixedNumericArray:', mixedNumericArray.join());
+console.log('Sorted without a compare function:', mixedNumericArray.sort());
+console.log('Sorted with compareNumbers:', mixedNumericArray.sort(compareNumbers));
+
+ +

이 예제는 다음 출력을 생성합니다. 결과가 보여 주듯이 비교 함수가 사용되면 숫자는 숫자 또는 숫자 문자열인지 여부에 관계없이 올바르게 정렬됩니다.

+ +
stringArray: Blue,Humpback,Beluga
+Sorted: Beluga,Blue,Humpback
+
+numberArray: 40,1,5,200
+Sorted without a compare function: 1,200,40,5
+Sorted with compareNumbers: 1,5,40,200
+
+numericStringArray: 80,9,700
+Sorted without a compare function: 700,80,9
+Sorted with compareNumbers: 9,80,700
+
+mixedNumericArray: 80,9,700,40,1,5,200
+Sorted without a compare function: 1,200,40,5,700,80,9
+Sorted with compareNumbers: 1,5,9,40,80,200,700
+
+ +

비 ASCII 문자 정렬

+ +

ASCII 이외의 문자, 즉 악센트 부호가있는 문자 (e, é, è, a, ä 등)가있는 문자열을 정렬하려면 영어가 아닌 다른 언어의 문자열에 {{jsxref ( "String.localeCompare")}}를 사용하십시오. 이 함수는 해당 문자를 비교하여 올바른 순서로 나타낼 수 있습니다.

+ +
var items = ['réservé', 'premier', 'cliché', 'communiqué', 'café', 'adieu'];
+items.sort(function (a, b) {
+  return a.localeCompare(b);
+});
+
+// items is ['adieu', 'café', 'cliché', 'communiqué', 'premier', 'réservé']
+
+ +

map을 사용한 정렬

+ +

compareFunction은 배열 내의 요소마다 여러 번 호출될 수 있습니다. 이러한 compareFunction의 성질에 따라,  높은 오버헤드가 발생할 수도 있습니다. compareFunction이 복잡해지고, 정렬할 요소가 많아질 경우, map을 사용한 정렬을 고려해보는 것이 좋습니다. 이 방법은 임시 배열을 하나 만들어서 여기에 실제 정렬에 사용할 값만을 뽑아서 넣어서 이를 정렬하고, 그 결과를 이용해서 실제 정렬을 하는 것입니다.

+ +
// 소트 할 배열
+var list = ['Delta', 'alpha', 'CHARLIE', 'bravo'];
+
+// 임시 배열은 위치 및 정렬 값이있는 객체를 보유합니다.
+var mapped = list.map(function(el, i) {
+  return { index: i, value: el.toLowerCase() };
+})
+
+// 축소 치를 포함한 매핑 된 배열의 소트
+mapped.sort(function(a, b) {
+  return +(a.value > b.value) || +(a.value === b.value) - 1;
+});
+
+// 결과 순서를 위한 컨테이너
+var result = mapped.map(function(el){
+  return list[el.index];
+});
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.4.4.11', 'Array.prototype.sort')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-array.prototype.sort', 'Array.prototype.sort')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.sort', 'Array.prototype.sort')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ +
{{Compat("javascript.builtins.Array.sort")}}
+ +
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/splice/index.html b/files/ko/web/javascript/reference/global_objects/array/splice/index.html new file mode 100644 index 0000000000..eb2a09af12 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/splice/index.html @@ -0,0 +1,153 @@ +--- +title: Array.prototype.splice() +slug: Web/JavaScript/Reference/Global_Objects/Array/splice +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/splice +--- +
{{JSRef}}
+ +

splice() 메서드는 배열의 기존 요소를 삭제 또는 교체하거나 새 요소를 추가하여 배열의 내용을 변경합니다.

+ +
{{EmbedInteractiveExample("pages/js/array-splice.html")}}
+ + + +

구문

+ +
array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
+
+ +

매개변수

+ +
+
start
+
배열의 변경을 시작할 인덱스입니다. 배열의 길이보다 큰 값이라면 실제 시작 인덱스는 배열의 길이로 설정됩니다. 음수인 경우 배열의 끝에서부터 요소를 세어나갑니다(원점 -1, 즉 -n이면 요소 끝의 n번째 요소를 가리키며 array.length - n번째 인덱스와 같음). 값의 절대값이 배열의 길이 보다 큰 경우 0으로 설정됩니다.
+
deleteCount {{optional_inline}}
+
배열에서 제거할 요소의 수입니다.
+
deleteCount를 생략하거나 값이 array.length - start보다 크면 start부터의 모든 요소를 제거합니다.
+
deleteCount가 0 이하라면 어떤 요소도 제거하지 않습니다. 이 때는 최소한 하나의 새로운 요소를 지정해야 합니다.
+
item1, item2, ... {{optional_inline}}
+
배열에 추가할 요소입니다. 아무 요소도 지정하지 않으면 splice()는 요소를 제거하기만 합니다.
+
+ +

반환 값

+ +

제거한 요소를 담은 배열. 하나의 요소만 제거한 경우 길이가 1인 배열을 반환합니다. 아무 값도 제거하지 않았으면 빈 배열을 반환합니다.

+ +

설명

+ +

만약 제거할 요소의 수와 추가할 요소의 수가 다른 경우 배열의 길이는 달라집니다.

+ +

예제

+ +

하나도 제거하지 않고, 2번 인덱스에 "drum" 추가

+ +
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
+var removed = myFish.splice(2, 0, 'drum');
+
+// myFish is ["angel", "clown", "drum", "mandarin", "sturgeon"]
+// removed is [], no elements removed
+ +

하나도 제거하지 않고, 2번 인덱스에 "drum"과 "guitar" 추가

+ +
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
+var removed = myFish.splice(2, 0, 'drum', 'guitar');
+
+// myFish is ["angel", "clown", "drum", "guitar", "mandarin", "sturgeon"]
+// removed is [], no elements removed
+
+ +

3번 인덱스에서 한 개 요소 제거

+ +
var myFish = ['angel', 'clown', 'drum', 'mandarin', 'sturgeon'];
+var removed = myFish.splice(3, 1);
+
+// removed is ["mandarin"]
+// myFish is ["angel", "clown", "drum", "sturgeon"]
+
+ +

2번 인덱스에서 한 개 요소 제거하고 "trumpet" 추가

+ +
var myFish = ['angel', 'clown', 'drum', 'sturgeon'];
+var removed = myFish.splice(2, 1, 'trumpet');
+
+// myFish is ["angel", "clown", "trumpet", "sturgeon"]
+// removed is ["drum"]
+ +

0번 인덱스에서 두 개 요소 제거하고 "parrot", "anemone", "blue" 추가

+ +
var myFish = ['angel', 'clown', 'trumpet', 'sturgeon'];
+var removed = myFish.splice(0, 2, 'parrot', 'anemone', 'blue');
+
+// myFish is ["parrot", "anemone", "blue", "trumpet", "sturgeon"]
+// removed is ["angel", "clown"]
+ +

2번 인덱스에서 두 개 요소 제거

+ +
var myFish = ['parrot', 'anemone', 'blue', 'trumpet', 'sturgeon'];
+var removed = myFish.splice(myFish.length - 3, 2);
+
+// myFish is ["parrot", "anemone", "sturgeon"]
+// removed is ["blue", "trumpet"]
+ +

-2번 인덱스에서 한 개 요소 제거

+ +
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
+var removed = myFish.splice(-2, 1);
+
+// myFish is ["angel", "clown", "sturgeon"]
+// removed is ["mandarin"]
+ +

2번 인덱스를 포함해서 이후의 모든 요소 제거

+ +
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
+var removed = myFish.splice(2);
+
+// myFish is ["angel", "clown"]
+// removed is ["mandarin", "sturgeon"]
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.12', 'Array.prototype.splice')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.splice', 'Array.prototype.splice')}}{{Spec2('ES6')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Array.splice")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/tolocalestring/index.html b/files/ko/web/javascript/reference/global_objects/array/tolocalestring/index.html new file mode 100644 index 0000000000..4fc1bd7f1a --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/tolocalestring/index.html @@ -0,0 +1,195 @@ +--- +title: Array.prototype.toLocaleString() +slug: Web/JavaScript/Reference/Global_Objects/Array/toLocaleString +tags: + - Array + - Internationalization + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/toLocaleString +--- +
{{JSRef}}
+ +

toLocaleString() 메서드는 배열의 요소를 나타내는 문자열을 반환합니다. 요소는 toLocaleString 메서드를 사용하여 문자열로 변환되고 이 문자열은 locale 고유 문자열(가령 쉼표 “,”)에 의해 분리됩니다.

+ +

{{EmbedInteractiveExample("pages/js/array-tolocalestring.html")}}

+ +

구문

+ +
arr.toLocaleString([locales[, options]]);
+ +

매개변수

+ +
+
locales {{optional_inline}}
+
A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the locales argument, see the {{jsxref("Intl")}} page.
+
options {{optional_inline}}
+
An object with configuration properties, for numbers see {{jsxref("Number.prototype.toLocaleString()")}}, and for dates see {{jsxref("Date.prototype.toLocaleString()")}}.
+
+ +

반환 값

+ +

배열의 요소를 표현하는 문자열.

+ +

설명

+ +

배열의 요소는 toLocaleString 메서드를 사용하여 문자열로 변환됩니다:

+ + + +

예제

+ +

toLocaleString 사용

+ +
var number = 1337;
+var date = new Date();
+var myArr = [number, date, 'foo'];
+
+var str = myArr.toLocaleString();
+
+console.log(str);
+// '1337,6.12.2013 19:37:35,foo' 출력(log)
+// Europe/Berlin 시간대로 German (de-DE) locale에서 실행하는 경우
+
+ +

폴리필

+ +
// https://tc39.github.io/ecma402/#sup-array.prototype.tolocalestring
+if (!Array.prototype.toLocaleString) {
+  Object.defineProperty(Array.prototype, 'toLocaleString', {
+    value: function(locales, options) {
+      // 1. Let O be ? ToObject(this value).
+      if (this == null) {
+        throw new TypeError('"this" is null or not defined');
+      }
+
+      var a = Object(this);
+
+      // 2. Let len be ? ToLength(? Get(A, "length")).
+      var len = a.length >>> 0;
+
+      // 3. Let separator be the String value for the
+      //    list-separator String appropriate for the
+      //    host environment's current locale (this is
+      //    derived in an implementation-defined way).
+      // NOTE: In this case, we will use a comma
+      var separator = ',';
+
+      // 4. If len is zero, return the empty String.
+      if (len === 0) {
+        return '';
+      }
+
+      // 5. Let firstElement be ? Get(A, "0").
+      var firstElement = a[0];
+      // 6. If firstElement is undefined or null, then
+      //  a.Let R be the empty String.
+      // 7. Else,
+      //  a. Let R be ?
+      //     ToString(?
+      //       Invoke(
+      //        firstElement,
+      //        "toLocaleString",
+      //        « locales, options »
+      //       )
+      //     )
+      var r = firstElement == null ?
+        '' : firstElement.toLocaleString(locales, options);
+
+      // 8. Let k be 1.
+      var k = 1;
+
+      // 9. Repeat, while k < len
+      while (k < len) {
+        // a. Let S be a String value produced by
+        //   concatenating R and separator.
+        var s = r + separator;
+
+        // b. Let nextElement be ? Get(A, ToString(k)).
+        var nextElement = a[k];
+
+        // c. If nextElement is undefined or null, then
+        //   i. Let R be the empty String.
+        // d. Else,
+        //   i. Let R be ?
+        //     ToString(?
+        //       Invoke(
+        //        nextElement,
+        //        "toLocaleString",
+        //        « locales, options »
+        //       )
+        //     )
+        r = nextElement == null ?
+          '' : nextElement.toLocaleString(locales, options);
+
+        // e. Let R be a String value produced by
+        //   concatenating S and R.
+        r = s + r;
+
+        // f. Increase k by 1.
+        k++;
+      }
+
+      // 10. Return R.
+      return r;
+    }
+  });
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('ES3')}}{{Spec2('ES3')}}초기 정의.
{{SpecName('ES5.1', '#sec-15.2.4.3', 'Array.prototype.toLocaleString')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.tolocalestring', 'Array.prototype.toLocaleString')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.tolocalestring', 'Array.prototype.toLocaleString')}}{{Spec2('ESDraft')}} 
{{SpecName('ES Int Draft', '#sup-array.prototype.tolocalestring', 'Array.prototype.toLocaleString')}}{{Spec2('ES Int Draft')}}This definition supersedes the definition provided in ECMA-262.
+ +

브라우저 호환성

+ +

{{Compat("javascript.builtins.Array.toLocaleString")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/tosource/index.html b/files/ko/web/javascript/reference/global_objects/array/tosource/index.html new file mode 100644 index 0000000000..e503b9c617 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/tosource/index.html @@ -0,0 +1,71 @@ +--- +title: Array.prototype.toSource() +slug: Web/JavaScript/Reference/Global_Objects/Array/toSource +tags: + - Array + - JavaScript + - Method + - Non-standard + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/toSource +--- +
{{JSRef}} {{non-standard_header}}
+ +

toSource() 메서드는 해당 배열의 소스 코드를 문자열로 반환합니다.

+ +

구문

+ +
arr.toSource()
+ +

반환 값

+ +

배열의 소스 코드를 나타내는 문자열을 반환합니다.

+ +

설명

+ +

toSource 메서드는 다음의 값을 반환합니다.

+ + + +

이 메서드는 보통 코드에 명시되지 않고 자바스크립트 내부적으로 호출됩니다. 디버깅을 위해 toSource를 호출하여 배열의 내용을 검사할 수 있습니다.

+ +

예제

+ +

배열의 소스 코드 검사하기

+ +

다음 코드는 배열의 소스 코드 문자열을 생성합니다.

+ +
var alpha = new Array('a', 'b', 'c');
+
+alpha.toSource();
+//returns ['a', 'b', 'c']
+
+ +

명세

+ +

Not part of any standard. Implemented in JavaScript 1.3.

+ +

브라우저 호환성

+ +
+ + +

{{Compat("javascript.builtins.Array.toSource")}}

+
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/tostring/index.html b/files/ko/web/javascript/reference/global_objects/array/tostring/index.html new file mode 100644 index 0000000000..9a1179be14 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/tostring/index.html @@ -0,0 +1,80 @@ +--- +title: Array.prototype.toString() +slug: Web/JavaScript/Reference/Global_Objects/Array/toString +tags: + - Array + - JavaScript + - Method + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Array/toString +--- +
{{JSRef}}
+ +

toString() 메서드는 지정된 배열 및 그 요소를 나타내는 문자열을 반환합니다.

+ +

{{EmbedInteractiveExample("pages/js/array-tostring.html")}}

+ +

구문

+ +
arr.toString()
+ +

반환 값

+ +

배열을 표현하는 문자열을 반환합니다.

+ +

설명

+ +

{{jsxref("Array")}} 객체는 {{jsxref("Object")}}의 toString 메서드를 재정의(override)합니다. Array 객체에 대해, toString 메서드는 배열을 합쳐(join) 쉼표로 구분된 각 배열 요소를 포함하는 문자열 하나를 반환합니다. 예를 들어, 다음 코드는 배열을 생성하며 그 배열을 문자열로 변환하기 위해 toString을 사용합니다.

+ +
var monthNames = ['Jan', 'Feb', 'Mar', 'Apr'];
+var myVar = monthNames.toString(); // 'Jan,Feb,Mar,Apr'을 myVar에 할당.
+
+ +

JavaScript는 배열이 텍스트 값으로 표현되거나 배열이 문자열 연결(concatenation)에 참조될 때 자동으로 toString 메서드를 호출합니다.

+ +

ECMAScript 5 의미

+ +

JavaScript 1.8.5 (Firefox 4)부터, ECMAScript 제5판 의미(semantics)와 일치하는 toString() 메서드는 일반(generic) 메서드이므로 모든 객체에 사용될 수 있습니다. 객체가 join() 메서드가 있는 경우, 호출되어 그 값이 반환됩니다. 그렇지 않으면 {{jsxref("Object.prototype.toString()")}}가 호출되어 그 결과값이 반환됩니다.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('ES1')}}{{Spec2('ES1')}}초기 정의. JavaScript 1.1에서 구현됨.
{{SpecName('ES5.1', '#sec-15.4.4.2', 'Array.prototype.toString')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.tostring', 'Array.prototype.toString')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.tostring', 'Array.prototype.toString')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

{{Compat("javascript.builtins.Array.toString")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/unshift/index.html b/files/ko/web/javascript/reference/global_objects/array/unshift/index.html new file mode 100644 index 0000000000..c4a03fd091 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/unshift/index.html @@ -0,0 +1,91 @@ +--- +title: Array.prototype.unshift() +slug: Web/JavaScript/Reference/Global_Objects/Array/unshift +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/unshift +--- +
{{JSRef}}
+ +

unshift() 메서드는 새로운 요소를 배열의 맨 앞쪽에 추가하고, 새로운 길이를 반환합니다.

+ +

{{EmbedInteractiveExample("pages/js/array-unshift.html")}}

+ +

구문

+ +
arr.unshift([...elementN])
+ +

매개변수

+ +
+
elementN
+
배열 맨 앞에 추가할 요소.
+
+ +

반환 값

+ +

메서드를 호출한 배열의 새로운 {{jsxref("Array.length", "length")}} 속성.

+ +

설명

+ +

unshift 메서드는 배열 형태의 객체 시작점에 주어진 값을 삽입합니다.

+ +

unshift는 제네릭하도록 설계되었으며, 배열 형태를 가진 객체가 {{jsxref("Function.call", "호출", "", 1)}}하거나 객체에 {{jsxref("Function.apply", "적용", "", 1)}}할 수 있습니다. length 속성을 가지지 않고, 대신 마지막 요소를 0부터 시작하는 순차적 인덱스로만 나타내는 객체에서는 의도한 것과 다르게 행동할 수 있습니다.

+ +

예제

+ +
var arr = [1, 2];
+
+arr.unshift(0); // result of call is 3, the new array length
+// arr is [0, 1, 2]
+
+arr.unshift(-2, -1); // = 5
+// arr is [-2, -1, 0, 1, 2]
+
+arr.unshift([-3]);
+// arr is [[-3], -2, -1, 0, 1, 2]
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
명세상태비고
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.13', 'Array.prototype.unshift')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.unshift', 'Array.prototype.unshift')}}{{Spec2('ES6')}} 
+ +

브라우저 호환성

+ +

{{Compat("javascript.builtins.Array.unshift")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/values/index.html b/files/ko/web/javascript/reference/global_objects/array/values/index.html new file mode 100644 index 0000000000..eb66adb964 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/values/index.html @@ -0,0 +1,87 @@ +--- +title: Array.prototype.values() +slug: Web/JavaScript/Reference/Global_Objects/Array/values +tags: + - Array + - ECMAScript 2015 + - Iterator + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/values +--- +
{{JSRef}}
+ +

values() 메서드는 배열의 각 인덱스에 대한 값을 가지는 새로운 Array Iterator 객체를 반환합니다.

+ +

{{EmbedInteractiveExample("pages/js/array-values.html")}}

+ +

구문

+ +
arr.values()
+
+ +

반환 값

+ +

새로운 {{jsxref("Array")}} 반복기 객체.

+ +

예제

+ +

for...of 루프를 통한 반복

+ +
var arr = ['w', 'y', 'k', 'o', 'p'];
+var eArr = arr.values();
+// your browser must support for..of loop
+// and let-scoped variables in for loops
+for (let letter of eArr) {
+  console.log(letter);
+}
+
+ +

다른 반복법

+ +
var arr = ['w', 'y', 'k', 'o', 'p'];
+var eArr = arr.values();
+console.log(eArr.next().value); // w
+console.log(eArr.next().value); // y
+console.log(eArr.next().value); // k
+console.log(eArr.next().value); // o
+console.log(eArr.next().value); // p
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
명세상태비고
{{SpecName('ES2015', '#sec-array.prototype.values', 'Array.prototype.values')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.prototype.values', 'Array.prototype.values')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

{{Compat("javascript.builtins.Array.values")}}

+ +

같이 보기

+ + -- cgit v1.2.3-54-g00ecf