프로그래밍/JavaScript
[JS] includes와 indexOf의 차이점
hi-rachel
2023. 6. 20. 00:06
배열에 특정 값이 존재하는지 확인하는 코드를 작성하다 includes와 indexOf 모두 사용할 수 있어 두 개의 차이점이 궁금해졌다.
배열에 찾는 특정 값이 있다면 includes는 true, 없다면 false 반환.
indexOf는 있다면 그 값의 index, 없다면 -1을 반환한다.
새로 안 사실
https://stackoverflow.com/questions/35370222/array-prototype-includes-vs-array-prototype-indexof
Array.prototype.includes vs. Array.prototype.indexOf
Beyond the improved readability, is there any advantage to includes over indexOf? They seem identical to me. What is the difference between this var x = [1,2,3].indexOf(1) > -1; //true And t...
stackoverflow.com
다른 차이를 알아보니 includes는 배열 안의 NaN 유무까지 판단할 수 있고 indexOf는 찾지 못한다.
if (arr.indexOf(el) !== -1) {
...
}
if (arr.includes(el)) {
...
}
배열의 값이 있는지 조건문으로 활용할 때는 위와 같이 둘 다 사용할 수 있다. + 성능에서도 큰 차이 없다고 한다.
값의 index가 필요하다면 indexOf를 사용, 둘의 반환값이 다르다는 것만 주의하자.