My Wiki (CodesStates)/JS,Node

(2-3) JS/Node 배열, 객체 - 배열 요소 포함 여부 확인하기

Esoolgnah 2021. 8. 1. 17:32
728x90

 

.indexOf ( 요소 ) : 원하는 요소가 어느 인덱스에 들어가 있는지 알 수 있다.

let words = ['Radagast', 'the', 'Brown'];

words.indexOf('the')
// 1
words.indexOf('Brown')
// 2
words.indexOf('Radagast')
// 0

 

단어가 없으면 -1이 반환된다.

words.indexOf('Radgast')
// 0
words.indexOf('없는단어')
// -1
words.indexOf('다른 것')
// -1

 

indexOf를 통해 단어가 있는지 없는지 알아내려면 이렇게 할 수 있다.

words.indexOf('Brown') !== -1
// true
words.indexOf('없는단어') !== -1
// false

 

대, 소문자를 잘 구분해야한다.

words.indexOf('brown')
// -1
words.indexOf('Brown')
// 2

 

함수를 사용해서 단어가 있는지 없는지 찾아내는 방법이다.

function hasElement(arr, element) {
  let isParent = arr.indexOf(element) !== -1;
  return isParent;
}

hasElement(words, 'Brown')
// true
hasElement(words, '없는것')
// false

 

 

.includes( 요소 ) : 요소의 포함 여부를 알 수 있다.

굳이 함수를 안 만들어도 include로 여부를 알 수 있다.

words.includes('Brown')
// true
words.includes('없는것')
// false

 

 

indexOf 와 includes 중 하나를 알아야 한다면 indexOf를 알아야한다. 범용성, 호환성이 더 좋다.
includes 는 인터넷 익스플로러에서 호환되지 않는다.

 

 

 

 

반응형