• 회원가입
  • 로그인
  • 구글아이디로 로그인

[Array] JS - findIndex() 메서드 - 맨처음 조건 충족/일치 배열값 색인번호 찾기 (= findIndex메서드 = 파인드인덱스메서드)

목차
  1. array.findIndex() 예제 - 15 이상인 첫번째 일치요소 색인번호 찾기
  2. array.findIndex() 정의
  3. array.findIndex() 구문
  4. array.findIndex() 예제 - 입력값보다 큰 첫번째 일치요소 색인번호 찾기

 

array.findIndex() 예제 - 15 이상인 첫번째 일치요소 색인번호 찾기 

 

<button onclick="homzzang()">클릭</button>


<p id="demo"></p>


<script>

var nums = [5, 10, 15, 20];


function checkNum(num) {

  return num >= 15;

}


function homzzang() {

  document.getElementById("demo").innerHTML = nums.findIndex(checkNum);

}

</script>

 

결과값: 2

 

array.findIndex() 정의

 

각 배열 요소에 함수 적용 후, 일치하는 첫 번째 요소의 색인번호 반환.

 


 

1.

  • 일치하는 요소 없으면, -1 반환.
  • 빈 배열요소에 대해선 실행 X
  • 원래 배열 변경 X

 

2.

  • ECMAScript6 (ES6: JavaScript 2015)
  • IE 제외한 주요 최신 브라우저 모두 지원.

 

3. 관련글

 

 

4. MDN findIndex() 예제 보기

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex

 

 

array.findIndex() 구문

 

array.findIndex(function(value, key, arr), thisValue)

 


[매개변수]

 

function()

필수. 배열 각 요소에 대해 실행할 함수

  • value - 필수. 현재요소의 값
  • key - 선택. 현재요소의 키
  • arr - 선택. 현재요소가 속한 배열


thisValue

선택. this 값으로 함수에 전달된 값 (기본값: undefined)

 


[반환값]

 

  • 일치요소 존재 O 경우, 일치요소의 첫번째 색인번호 반환.
  • 일치요소 존재 X 경우, -1 반환.

 

 

array.findIndex() 예제 - 입력값보다 큰 첫번째 일치요소 색인번호 찾기

 

<input type="number" id="hz" value="5"></p>


<button onclick="homzzang()">클릭</button>


<p id="demo"></p>


<script>

const nums = [1, 3, 6, 10];


function checkValue(x) {

  return x > document.getElementById("hz").value;

}


function homzzang() {

  document.getElementById("demo").innerHTML = nums.findIndex(checkValue);

}

</script>


결과값: 사용자 입력값에 따라 결과값 다름.



분류 제목
Conversion JS - function(){} 타입변환 - (숫자: NaN , 문자열: "function(){}" , 참…
Conversion JS - { } 타입변환 - (숫자: NaN , 문자열: "[object Object]" , 참거짓: tru…
Conversion JS - null 타입변환 - (숫자: 0 , 문자열: "null" , 참거짓: false)
Conversion JS - undefined 타입변환 - (숫자: NaN , 문자열: "undefined" , 참거짓: fal…
DOM_Attribute JS - Attribute Object -
DOM_Attribute JS - attribute.isId 속성 - 속성이 아이디유형인지 반환. (모든 브라우저 지원X)
DOM_Attribute JS - attr.name -
DOM_Attribute JS - attr.value - 요소 속성값 반환/설정 (= value속성 = 밸류속성)
DOM_Attribute JS - attr.specified -
DOM_Attribute JS - nodemap.getNamedItem() 메서드 -
DOM_Attribute JS - nodemap.item() 메서드 -
DOM_Attribute JS - nodemap.length -
DOM_Attribute JS - nodemap.removeNamedItem() 메서드 -
DOM_Attribute JS - nodemap.setNamedItem() 메서드 -
DOM_Attribute JS - attr.appendChild() 메서드 - 사용금지
DOM_Attribute JS - attr.attributes - 사용금지
DOM_Attribute JS - attr.baseURI - 사용금지
DOM_Attribute JS - attr.childNodes - 사용금지
DOM_Attribute JS - attr.cloneNode() 메서드 - 사용금지
DOM_Attribute JS - attr.firstChild -
20/67
목록
찾아주셔서 감사합니다. Since 2012