diff options
author | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:42:17 -0500 |
---|---|---|
committer | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:42:17 -0500 |
commit | da78a9e329e272dedb2400b79a3bdeebff387d47 (patch) | |
tree | e6ef8aa7c43556f55ddfe031a01cf0a8fa271bfe /files/ko/web/javascript/reference/global_objects/array/find | |
parent | 1109132f09d75da9a28b649c7677bb6ce07c40c0 (diff) | |
download | translated-content-da78a9e329e272dedb2400b79a3bdeebff387d47.tar.gz translated-content-da78a9e329e272dedb2400b79a3bdeebff387d47.tar.bz2 translated-content-da78a9e329e272dedb2400b79a3bdeebff387d47.zip |
initial commit
Diffstat (limited to 'files/ko/web/javascript/reference/global_objects/array/find')
-rw-r--r-- | files/ko/web/javascript/reference/global_objects/array/find/index.html | 226 |
1 files changed, 226 insertions, 0 deletions
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 +--- +<div>{{JSRef}}</div> + +<p><code><strong>find()</strong></code><strong> </strong>메서드는 주어진 판별 함수를 만족하는 <strong>첫 번째 요소</strong>의 <strong>값</strong>을 반환합니다. 그런 요소가 없다면 {{jsxref("undefined")}}를 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-find.html")}}</div> + + + +<p>찾은 요소의 값 대신 <strong>인덱스</strong>를 반환하는 {{jsxref("Array.findIndex", "findIndex()")}} 메서드도 살펴보세요.</p> + +<p>배열 요소의 위치를 찾고자 하는 경우에는 {{jsxref("Array.prototype.indexOf()")}}를 사용하세요.</p> + +<p>배열 요소가 해당 배열에 존재하는지 확인하고자 하는 경우에는 {{jsxref("Array.prototype.indexOf()")}} 또는 {{jsxref("Array.prototype.includes()")}}를 사용세요.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code><var>arr</var>.find(<var>callback</var>[, <var>thisArg</var>])</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>callback</code></dt> + <dd>배열의 각 값에 대해 실행할 함수. 아래의 세 인자를 받습니다. + <dl> + <dt><code>element</code></dt> + <dd>콜백함수에서 처리할 현재 요소.</dd> + <dt><code>index</code>{{optional_inline}}</dt> + <dd>콜백함수에서 처리할 현재 요소의 인덱스.</dd> + <dt><code>array</code>{{optional_inline}}</dt> + <dd><code>find</code> 함수를 호출한 배열.</dd> + </dl> + </dd> + <dt><code>thisArg</code></dt> + <dd>선택 항목. 콜백이 호출될 때 <code>this</code>로 사용할 객체.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>주어진 판별 함수를 만족하는 <strong>첫 번째 요소</strong>의 <strong>값</strong>. 그 외에는 {{jsxref("undefined")}}.</p> + +<h2 id="설명">설명</h2> + +<p><code>find</code> 메서드는 <code>callback</code> 함수가 참을 반환 할 때까지 해당 배열의 각 요소에 대해서 <code>callback</code> 함수를 실행합니다. 만약 어느 요소를 찾았다면 <code>find</code> 메서드는 해당 요소의 값을 즉시 반환하고, 그렇지 않았다면 {{jsxref("undefined")}}를 반환합니다. <code>callback</code>은 <code>0</code> 부터 <code>length - 1</code> 까지 배열의 모든 인덱스에 대해 호출되며, 값이 지정되지 않은 요소도 포함하여 모든 인덱스에 대해 호출됩니다. 따라서, 희소 배열 (sparse arrays)의 경우에는 값이 지정된 요소만 탐색하는 다른 메소드에 비해 더 비효율적입니다.</p> + +<p><code>callback</code>은 다음의 세가지 인자를 가지고 호출됩니다: 요소의 값, 요소의 인덱스, 순회의 대상이 되는 배열. </p> + +<p><code>thisArg</code> 파라미터가 주어진 경우에는 제공되었다면 <code>thisArg</code>가 <code>callback</code>안에서 <code>this</code>로 사용되고, 그렇지 않은 경우 {{jsxref("undefined")}} 가 <code>this</code>로 사용됩니다. </p> + +<p><code>find</code>는 호출의 대상이 된 배열을 변경(mutate)하지 않습니다.</p> + +<p><code>find</code>가 처리할 배열 요소의 범위는 첫 <code>callback</code>이 호출되기 전에 먼저 결정됩니다. <code>find</code>메서드가 실행 된 이후에 배열에 추가된 요소들에 대해서는 <code>callback</code>이 호출되지 않습니다. 아직 <code>callback</code>이 호출되지 않았던 배열 요소가 <code>callback</code>에 의해서 변경된 경우, <code>find</code>가 해당 요소의 인덱스를 방문할 때의 값으로 <code>callback</code>함수에 전달될 것입니다. 즉, 삭제된 요소에도 <code>callback</code>이 호출됩니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="속성_중_하나를_사용하여_배열에서_객체_찾기">속성 중 하나를 사용하여 배열에서 객체 찾기</h3> + +<pre class="brush: js">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 } +</pre> + +<h4 id="ES2015_화살표_함수_사용하기">ES2015 화살표 함수 사용하기</h4> + +<p> </p> + +<pre class="brush: js">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 }</pre> + +<p> </p> + +<h3 id="배열에서_소수_찾기">배열에서 소수 찾기</h3> + +<p>다음 예제에서는 배열의 요소 중 소수인 요소를 찾습니다(소수가 없는 경우에는 {{jsxref("undefined")}}를 반환).</p> + +<pre class="brush: js">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 +</pre> + +<h3 id="탐색_중_삭제된_배열_요소">탐색 중 삭제된 배열 요소</h3> + +<p>다음 예제에서는 삭제되어 존재하지 않는 배열의 요소에도 <code>callback</code>이 호출되어 해당 시점의 값이 <code>callback</code>에 전달되는 것을 보여줍니다.</p> + +<pre class="brush: js">// 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); +}); +</pre> + +<h2 id="폴리필">폴리필</h2> + +<p><code>find</code>는 ECMAScript 2015 명세에 추가됐으므로 어떤 표준 구현체에서는 사용지 못할 수도 있습니다. 다른 모든 코드 이전에 아래 코드를 포함하면 <code>find</code>를 지원하지 않는 환경에서도 사용할 수 있습니다.</p> + +<pre class="brush: js">// 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 + }); +}</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.find', 'Array.prototype.find')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.find', 'Array.prototype.find')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div>{{Compat("javascript.builtins.Array.find")}}</div> + +<div id="compat-mobile"> </div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("Array.prototype.findIndex()")}} – 찾기 이후 인덱스 반환</li> + <li>{{jsxref("Array.prototype.includes()")}} – 배열에 어떤 값이 존재하는지 검사</li> + <li>{{jsxref("Array.prototype.filter()")}} – 매칭되는 모든 요소 찾기</li> + <li>{{jsxref("Array.prototype.every()")}} – 모든 요소에 대해서 검사</li> +</ul> |