JavaScript
21.04.30 find(), findIndex(), indexOf()
슈팅스타제제
2021. 4. 30. 21:22
📌Array.prototype.find() : 값 찾기!!
find() 메서드는 주어진 판별 함수를 만족하는 첫번째 요소의 값을 반환한다.
그런 요소가 없다면 undefined를 반환한다.
const array1 = [5, 12, 8, 130, 44];
const found = array1.find(element => element > 10);
console.log(found);
//expected output : 12
📌Array.prototype.findIndex() : 위치 찾기!! 함수 조건
findIndex()메서드는 주어진 판별 함수를 만족하는 배열의 첫번째 요소에 대한 인덱스를 반환한다.
만족하는 요소가 없으면 -1을 반환한다.
const array1 = [5, 12, 8, 130, 44];
const isLargerNumber = (element)=>element > 13;
console.log(array1.findIndex(isLargerNumber));
//expected output : 3
📌Array.prototype.indexOf() : 위치 찾기!! 요소 조건
indexOf()메서드는 배열에서 지정된 요소를 찾을 수 있는 첫번째 인덱스를 반환하고 존재하지 않으면 -1을 반환한다.
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
console.log(beasts.indexOf('bison'));
//expected output : 1
console.log(beasts.indexOf('bison', 2));
//expected output : 4
console.log(beasts.indexOf('giraffe'));
//expected output : -1