목차

JavaScript Array findIndex()

  • description : JavaScript Array findIndex()
  • author : 오션
  • email : shlim@repia.com
  • lastupdate : 2022-12-29 Thu


JavaScript Array findIndex()

findIndex() 메소드는 배열의 각 요소들에 대해 함수를 실행합니다.
findIndex() 메소드는 테스트를 통과한 첫 번째 요소의 인텍스(위치)를 반환합니다.
findIndex() 메소드는 일치하는 것을 찾지 못했을 때 -1을 반환합니다.
findIndex() 메소드는 비어있는 배열의 요소들에 대해 함수를 실행하지 않습니다.
findIndex() 메소드는 기존의 배열을 변경하지 않습니다.

Syntax

array.findIndex(function(currentValue, index, arr), thisValue)

Parameters

Parameters Description
function() 필수. 배열의 각 요소에 대해 실행될 함수
currentValue 필수. 현재 요소의 값
index 선택. 현재 요소의 인덱스
arr 선택. 현재 요소의 배열
thisValue 선택. 기본설정은 **undefined*
this값으로 함수에 전달되는 값


Return Value

Type Description
A number 테스트를 통과한 첫 번째 요소의 인덱스
그렇지 않은 경우 -1


예제

예제1

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>findIndex()</title>
</head>
<body>
        <h1>JavaScript Arrays</h1>
        <h2>findIndex()</h2>
 
        <p>findIndex() returns the index of the first element that passes a test (provided by a function).</p>
 
        <p id="demo"></p>
 
        <p>findIndex() is not supported in Internet Explorer 11 (or earlier).</p>
 
        <script>
            const ages = [3, 10, 18, 20];
 
            // p#demo에 ages 배열에서 checkAge 함수가 반환한 값, 즉 18보다 큰 숫자인 20의 인텍스 3을 표시
            document.getElementById("demo").innerHTML = ages.findIndex(checkAge);
 
            // 18보다 큰 age를 반환하는 함수
            function checkAge(age) {
                return age > 18;
            }
 
        </script>
</body>
</html>


예제2

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>findIndex() Example</title>
</head>
<body>
 
    <h1>JavaScript</h1>
    <h2>findIndex() Method</h2>
 
    <p>Click "Test" to return the index of the first array element that has a value above this number:</p>
 
    <p><input type="number" id="toCheck" value="18"></p>
 
    <button onclick="myFunction()">Test</button>
 
    <p id="demo"></p>
 
    <p>findIndex() is not supported in Internet Explorer 11 (or earlier).</p>
 
    <script>
        const numbers = [4, 12, 16, 20];
 
        // input#toCheck의 값(여기서는 18)보다 큰 숫자를 반환하는 함수
        function checkValue(x) {
            return x > document.getElementById('toCheck').value;
        }
 
        // Test 버튼 클릭 시, p#demo에 numbers 배열에서 checkValue함수가 반환하는 값, 즉 18보다 큰 숫자를 찾아서 인텍스를 표시하는 함수
        function myFunction() {
            document.getElementById("demo").innerHTML = numbers.findIndex(checkValue); 
            // numbers 배열에서 18보다 큰 숫자 20의 인덱스 3을 표시한다.
        }
    </script>
</body>
</html>


예제3

const numbers = [4, 12, 16, 20];
 
let isLargeThan18 = numbers.find(function(element) {
    return element > 18;
});
console.log(`numbers 배열에서 18보다 큰 숫자는 ${isLargeThan18} 입니다.`);
// numbers 배열에서 18보다 큰 숫자는 20 입니다.
 
let isLargeThan18ArrowFunction = numbers.find((element) => element > 18);
console.log(`numbers 배열에서 18보다 큰 숫자는 ${isLargeThan18ArrowFunction} 입니다.`);
// numbers 배열에서 18보다 큰 숫자는 20 입니다.
 
let index = numbers.findIndex((element) => element > 18);
console.log(`numbers 배열에서 18보다 큰 숫자 요소의 인텍스는 ${index} 입니다.`);
// numbers 배열에서 18보다 큰 숫자 요소의 인텍스는 3 입니다.


예제4

let ranks = [1, 5, 7, 8, 10, 7];
let index = ranks.findIndex(rank => rank === 7);
// ranks 배열에서 숫자 7이 처음 나타나는 인덱스를 반환
 
console.log(index);     // 2


let ranks = [1, 5, 7, 8, 10, 7];
 
let index = ranks.findIndex(
    (rank, index) => rank === 7 && index > 2
    // ranks 배열에서 인덱스 2 이후에 숫자 7이 처음 나타나는 인덱스를 반환
);
 
console.log(index);     // 5


const products = [
    {name: 'Phone', price: 999}
    , {name: 'Computer', price: 1999}
    , {name: 'Tablet', price: 995}
];
 
const index = products.findIndex(product => product.price > 1000);
// 가격이 1000보다 큰 첫 번째 product의 인덱스를 반환
 
console.log(index); // 1

JavaScript Array findIndex()
Array.prototype.findIndex()
JavaScript Array findIndex() Method