48일차

JiHun·2023년 6월 20일

부트캠프

목록 보기
40/56

indexOf

공식문서를 찾아보니
Array.prototype.indexOf()
String.prototype.indexOf()

배열에도 쓰고 문자열에도 쓴다!

예시

const Items = [1, 2, 6, 4, 7];

Items.indexOf(1)   // 0
Items.indexOf(7)   // 7
Items.indexOf(3)   // -1

배열의 각 요소를 찾을 때, 찾을 수 있는 첫 번째 인덱스를 반환한다. 없으면 -1을 반환.

const animals = ['cat', 'dog', 'hamster', 'bird', 'cat']

animals.indexOf('cat')     // 0
animals.indexOf('bird')    // 3
animals.indexOf('cat', 2)  // 4
animals.indexOf('meerkat') // -1

두번째 파라미터로 숫자를 써주면, n번째 반복되는 요소의 인덱스를 반환한다.

-1이라는 값을 이용해 요소들이 배열에 있는지, 없는지 파악할 수 있다.
이와 같은 점에서 Array.prototype.includes()도 사용할 수 있다.
하지만 찾은 요소의 첫 번째 요소가 나오기 때문에 id나

findIndex

주어진 판별 함수를 만족하는 배열의 첫 번째 요소에 대한 인덱스를 반환한다.

const numbers = [1, 6, 2, 8, 19];

const moreSeven = numbers.findIndex(element => element > 7);
console.log(moreSeven); // 3

const moreTwenty = numbers.findIndex(element => element > 20);
console.log(moreTwenty); // -1

const eightIndex = numbers.findIndex(element => element === 8);
console.log(eightIndex);  // 3

판별함수를 쓸 수 있기 때문에 조건을 이용하여 찾을 수 있다.

이것도 발견되지 않으면 -1을 반환한다.

find

findIndex랑 비교해서 차이점이 있다면 findIndex는 요소의 인덱스를 반환하는 한편, find메서드는 요소의 값을 반환한다. 그런 요소가 없다면 undefined를 반환한다.

const numbers = [6,11,5,199,31];

const found = numbers.find(element=> element > 10);

console.log(found);   //  11;

some

배열 안의 어떤 요소라도 주어진 판별 함수를 적어도 하나라도 통과하는지 테스트한다.
판별 함수가 true를 반환하면 array.some()은 true를 반환한다. Boolean 값 반환.

const numbers = [1, 2, 3, 4, 5];

const odd = (element) => element % 2 === 0;
console.log(numbers.some(odd));   // true

console.log(numbers.some((num) => num > 10); // false;

every

배열 안의 모든 요소가 주어진 판별 함수를 통과하는지 테스트한다. Boolean 값 반환

const isBelowTen = (currentValue) => currentValue < 10;

const array = [1, 5, 2, 5, 6, 3];
console.log(array.every(isBelowTen)); // true;

마지막으로

filter와 map이 이제 조금 친해지려고하니 다른 애들이 튀어나왔다. filter, map을 더 중점적으로 파기는 해야겠지만, 이것도 알아야 한다고 생각해 따로 정리했다.

참조

MDN Array.prototype.indexOf()
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

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

MDN Array.prototype.find()
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/find

MDN Array.prototype.some()
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/some

MDN Array.prototype.every()
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/every

profile
안녕하세요. 프론트엔드 개발자 송지훈입니다.

0개의 댓글