TypedArray.findIndex() 함수란?
TypedArray(타입화 배열)의 findIndex() 함수는 콜백 함수를 인자로 받아, 배열의 각 요소가 해당 함수로 구현된 조건 테스트를 통과하는지 순서대로 검사합니다. 조건을 만족하는 첫 번째 요소의 인덱스(index)를 반환하며, 만족하는 요소가 하나도 없으면 -1을 반환합니다.
콜백 함수는 세 개의 매개변수를 전달받습니다. 현재 처리 중인 요소(element), 해당 요소의 인덱스(index), 그리고 findIndex()가 호출된 배열(array)입니다. 이 메서드는 Int32Array, Uint8Array, Float64Array 등 모든 종류의 타입화 배열에서 사용할 수 있습니다.
문법(Syntax)
typedArray.findIndex(function_name)
예제 1: 조건을 만족하는 요소의 인덱스 찾기
다음 예제에서는 배열에서 35보다 큰 값을 가진 첫 번째 요소의 인덱스를 찾습니다.
<html>
<head>
<title>JavaScript TypedArray findIndex 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) {
var ele = element>35;
return ele;
}
result = int32View.findIndex(testResult);
document.write("Result: "+result);
</script>
</body>
</html>출력 결과
Contents of the typed array: 21,19,65,21,14,66,87,55 Result: 2
배열에서 35보다 큰 첫 번째 값은 인덱스 2에 위치한 65입니다. 따라서 findIndex()는 해당 요소의 값이 아닌 인덱스인 2를 반환합니다.
예제 2: 조건을 만족하는 요소가 없는 경우
다음 예제에서는 100보다 큰 값을 찾도록 조건을 변경했습니다. 하지만 배열에 100을 초과하는 요소가 없기 때문에 -1이 반환됩니다.
<html>
<head>
<title>JavaScript TypedArray findIndex 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) {
var ele = element>100;
return ele;
}
result = int32View.findIndex(testResult);
document.write("Result: "+result);
</script>
</body>
</html>출력 결과
Contents of the typed array: 21,19,65,21,14,66,87,55 Result: -1
findIndex()와 find()의 차이점
두 메서드는 이름이 비슷하지만 반환값이 다릅니다. find()는 조건을 만족하는 요소의 값 자체를 반환하며, 조건에 맞는 요소가 없으면 undefined를 반환합니다. 반면 findIndex()는 조건을 만족하는 요소의 인덱스를 반환하고, 없으면 -1을 반환합니다. 따라서 요소의 위치 정보가 필요한 경우에는 findIndex()를 사용하는 것이 적합합니다.