find() 메서드는 자바스크립트의 TypedArray(타입 배열)에서 제공하는 내장 메서드로, 콜백 함수를 인수로 받아 배열의 각 요소가 해당 함수의 조건 테스트를 통과하는지 검사합니다. 조건을 만족하는 첫 번째 요소를 발견하면 그 값을 즉시 반환하고, 만족하는 요소가 하나도 없으면 undefined를 반환합니다.
주요 특징
- 조건을 만족하는 첫 번째 요소만 반환하며, 이후 요소는 더 이상 검사하지 않습니다.
- 조건에 맞는 요소가 없으면
undefined를 반환합니다. - 콜백 함수는
(element, index, array)세 개의 인수를 전달받을 수 있습니다. - 일반 Array의
find()와 동일하게 동작하지만, TypedArray 전용으로 최적화되어 있습니다.
문법(Syntax)
typedArray.find(callback(element, index, array))
콜백 함수는 각 요소에 대해 참(true) 또는 거짓(false)을 반환해야 하며, 처음으로 true를 반환한 시점의 요소가 결과값이 됩니다.
예제 1: 조건을 만족하는 첫 번째 요소 찾기
다음 예제는 Int32Array에서 35보다 큰 첫 번째 요소를 찾는 코드입니다.
<html>
<head>
<title>JavaScript TypedArray find Method</title>
</head>
<body>
<script type="text/javascript">
var int32View = new Int32Array([21, 19, 65, 21, 14, 66, 87, 55]);
document.write("Contents of the typed array: " + int32View);
document.write("<br>");
function testResult(element, index, array) {
return element > 35;
}
result = int32View.find(testResult);
document.write("Result: " + result);
</script>
</body>
</html>
실행 결과
Contents of the typed array: 21,19,65,21,14,66,87,55 Result: 65
배열을 왼쪽부터 순서대로 검사했을 때 35보다 큰 값은 세 번째 요소인 65입니다. 따라서 뒤에 있는 66, 87 같은 더 큰 값이 있더라도 검사가 중단되고 65가 반환됩니다.
예제 2: 조건을 만족하는 요소가 없는 경우
배열에 조건을 충족하는 요소가 존재하지 않으면 이 메서드는 undefined를 반환합니다.
<html>
<head>
<title>JavaScript TypedArray find Method</title>
</head>
<body>
<script type="text/javascript">
var int32View = new Int32Array([21, 19, 65, 21, 14, 66, 87, 55]);
document.write("Contents of the typed array: " + int32View);
document.write("<br>");
function testResult(element, index, array) {
return element > 100;
}
result = int32View.find(testResult);
document.write("Result: " + result);
</script>
</body>
</html>
실행 결과
Contents of the typed array: 21,19,65,21,14,66,87,55 Result: undefined
위 예제에서는 100보다 큰 요소가 배열에 없으므로 결과값으로 undefined가 출력됩니다.
정리
TypedArray의 find() 메서드는 대량의 숫자 데이터를 다룰 때 특정 조건을 만족하는 값을 빠르게 검색할 수 있는 유용한 도구입니다. 조건에 맞는 모든 요소가 필요하다면 filter(), 인덱스 위치가 필요하다면 findIndex() 메서드를 함께 활용하면 됩니다.