자바스크립트 배열 찾기()
실시예 1
값이 18보다 큰 첫 번째 요소의 값을 찾습니다.
const ages = [3, 10, 18, 20];
function checkAge(age) {
return age > 18;
}
function myFunction() {
document.getElementById("demo").innerHTML = ages.find(checkAge);
}
정의 및 사용
이 find()
메서드는 테스트를 통과한 첫 번째 요소의 값을 반환합니다.
이 find()
메서드는 각 배열 요소에 대해 함수를 실행합니다.
요소가 발견되지 않으면 find()
메서드가 반환 됩니다 .undefined
메서드 는 find()
빈 요소에 대해 함수를 실행하지 않습니다.
이 find()
방법은 원래 배열을 변경하지 않습니다.
통사론
array.find(function(currentValue, index, arr),thisValue)
매개변수
function() | Required. A function to 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. |
반환 값
유형 | 설명 |
가치 |
테스트를 통과한 첫 번째 요소의 값입니다. 그렇지 않으면 반환합니다 undefined . |
브라우저 지원
find()
ECMAScript6(ES6) 기능입니다.
ES6(JavaScript 2015)은 모든 최신 브라우저에서 지원됩니다.
Chrome | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes |
find()
Internet Explorer 11(또는 이전)에서는 지원되지 않습니다.
실시예 2
특정 숫자보다 큰 값을 갖는 첫 번째 요소의 값을 찾으십시오.
<p><input type="number" id="ageToCheck" value="18"></p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
const ages = [4, 12, 16, 20];
function checkAge(age) {
return age > document.getElementById("ageToCheck").value;
}
function myFunction() {
document.getElementById("demo").innerHTML = ages.find(checkAge);
}
</script>