javaScript
배열 메서드[indexOf(), includes()]
Doityoo
2022. 11. 2. 20:36
arr.indexOf()
배열의 요소(index)가 있는지? 있다면 몇번째에 존재하는지 알려주는 메서드.
let words = [’Radagast’, ‘the’, ‘Brown’];
words.indexOf('the') // 1
words.indexOf('Radagast') // 0
words.indexOf('없는단어') // -1
해당 배열에 index가 있다면? 0 < n
해당 배열에 index가 없다면? -1
const hasPresent = (arr, ele) => {
let isPresent = arr.indexOf(ele) !== -1;
return isPresent;
}
// isPresent === arr에 ele요소가 -1과 같지 않다면(존재 한다면)
hasPresent(words, "없는단어")
// false
hasPresent(words, "Brown")
// true
* indexOf()메서드는 찾고자 하는 배열에 같은 값의 element가 중복으로 존재한다면? 맨 앞의 element의 자리를 알려준다!
arr.includes()
indexOf()와 비슷하지만 다른점? 해당 배열에 요소가 존재하면 true! 없다면 false로 반환한다. 즉 boolean으로 반환한다.
words.includes('Brown') // true
words.includes('없는단어') // false