자바스크립트 배열 findIndex()
실시예 1
값이 18보다 큰 첫 번째 요소를 찾습니다.
const ages = [3, 10, 18, 20];
ages.findIndex(checkAge);
function checkAge(age) {
return age > 18;
}
정의 및 사용
이 findIndex()
메서드는 각 배열 요소에 대해 함수를 실행합니다.
이 findIndex()
메서드는 테스트를 통과한 첫 번째 요소의 인덱스(위치)를 반환합니다.
일치하는 항목 이 findIndex()
없으면 메서드는 -1을 반환합니다.
메서드 는 findIndex()
빈 배열 요소에 대해 함수를 실행하지 않습니다.
이 findIndex()
방법은 원래 배열을 변경하지 않습니다.
통사론
array.findIndex(function(currentValue, index, arr), thisValue)
매개변수
Parameter | Description |
function() | Required. A function to be run for each array element. |
currentValue | Required. The value of the current element. |
index | Optional. The index of the current element. |
arr | Optional. The array of the current element. |
thisValue | Optional. Default undefined .A value passed to the function as its this value. |
반환 값
유형 | 설명 |
번호 |
테스트를 통과한 첫 번째 요소의 인덱스입니다. 그렇지 않으면 -1입니다. |
브라우저 지원
findIndex()
ECMAScript6(ES6) 기능입니다.
ES6(JavaScript 2015)은 모든 최신 브라우저에서 지원됩니다.
Chrome | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes |
findIndex()
Internet Explorer 11(또는 이전)에서는 지원되지 않습니다.
더 많은 예
입력 값보다 큰 값을 가진 첫 번째 요소를 찾습니다.
<p><input type="number" id="toCheck" value="18"></p>
<button onclick="myFunction()">Test</button>
<p>Any values above: <span id="demo"></span></p>
<script>
const numbers = [4, 12, 16, 20];
function checkValue(x) {
return x > document.getElementById("toCheck").value;
}
function myFunction() {
document.getElementById("demo").innerHTML = numbers.findIndex(checkValue);
}
</script>