본문 바로가기
💻CODING/javascript

[js] find includes 차이

by 코딩하는 갓디노 2022. 1. 24.

find includes 차이

 

array에서 사용하는 메소드
find()와 includes()의 비교입니다.

 

array.find()

  • find() 메서드는 주어진 함수를 만족하는 첫 번째 요소의 값을 반환합니다.
  • 그런 요소가 없다면 undefinded를 반환합니다.
  • 찾은 요소의 값 대신 인덱스를 반환하는 것은 findIndex()
  • 요소의 위치를 찾고자 하는 경우에는 indexOf()
  • 배열 요소가 해당 배열에 존재하는지 확인하고자 하는 경우에는 Array.prototype.indexOf() 또는 Array.prototype.includes()를 사용세요.

 

array.find() 예시

const arr1 = [5, 30, 7, 120, 45];
const found = arr1.find(el => el > 10);
console.log(found);
//결과 30

 

array.findIndex() 예시

const arr1 = [5, 30, 7, 120, 45];
const found = arr1.findIndex(el => el > 10);
console.log(found);
//결과 1

 

여기서 주어진 조건에 만족하는 모든 요소를 찾기 위해서는 filter 메소드를 사용합니다.

array.filter() 예시

const arr1 = [5, 30, 7, 120, 45];
const found = arr1.filter(el => el > 10);
console.log(found);
//결과 [30, 120, 45]

 

String 또는 Array.indexOf()

  • String 문자열 또는 Array에 사용되는 메소드입니다. 
  • 호출한 String 객체 또는 배열에서 주어진 값과 일치하는 첫 번째 인덱스를 반환합니다.
  • 일치하는 값이 없으면 -1을 반환합니다. 

 

String.indexOf() 예시

'Blue Whale'.indexOf('Blue');     // returns  0
'Blue Whale'.indexOf('Blute');    // returns -1
'Blue Whale'.indexOf('blue'); // returns -1

 

Array.indexOf() 예시

const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
console.log(beasts.indexOf('camel'));
//결과 2

 

Array.includes()

  • 배열이 특정 요소를 포함하고 있는지 판별합니다.
  • boolean(true, false)를 반환합니다.
  • 검색 기능을 구현할때 주로 사용합니다. 

 

Array.includes() 예시

const arr1 = [5, 30, 7, 120, 45];
const found = arr1.includes(45);
console.log(found);
//결과 true

[1, 2, 3].includes(2);     // true
[1, 2, 3].includes(4);     // false

 

find includes 차이

 

find()는 조건을 지정하여 특정 값을 가져올 필요가 있을 때 사용하고 
includes()는 특정한 문자열에 대해 일치하는지 여부(true/false)를 확인할 때 사용합니다. 
조건문에서 true, flase만 체크하면 되는 경우,  
find를 사용할 경우 불필요한 메모리 누수를 시킬 수 있으니 
includes 사용을 권장합니다.

반응형

댓글