JavaScript Array.prototype.includes() 메서드란?
JavaScript의 Array.prototype.includes() 메서드는 배열에 특정 요소가 포함되어 있는지 확인하는 데 사용됩니다. 이 메서드는 해당 요소가 배열 안에 존재하면 true, 존재하지 않으면 false를 반환하므로, 조건문과 함께 활용하기 매우 편리합니다.
다음은 Array.prototype.includes() 메서드를 활용한 예제 코드입니다 −
예제
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.sample {
font-size: 20px;
font-weight: 500;
}
</style>
</head>
<body>
<h1>JavaScript Array includes()</h1>
<div class="sample"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to check if the array contains lion element or not</h3>
<script>
let fillEle = document.querySelector(".sample");
let arr = ["cow", "bull", "lion", "tiger", "sheep"];
fillEle.innerHTML = arr;
document.querySelector(".Btn").addEventListener("click", () => {
fillEle.innerHTML = "Lion is present in array: " + arr.includes("lion");
});
</script>
</body>
</html>출력 결과
위 코드를 실행하면 다음과 같은 화면이 나타납니다 −

“CLICK HERE” 버튼을 클릭하면 아래와 같이 배열에 'lion' 요소가 포함되어 있음을 확인할 수 있습니다 −

includes() 메서드의 주요 특징
- 반환값: 요소가 존재하면
true, 없으면false를 반환합니다. - 대소문자 구분: 문자열 비교 시 대소문자를 엄격하게 구분하므로, 'Lion'과 'lion'은 서로 다른 값으로 처리됩니다.
- fromIndex 지원: 두 번째 인수로 검색을 시작할 인덱스를 지정할 수 있습니다. 예를 들어
arr.includes("lion", 3)처럼 사용하면 3번 인덱스부터 검색합니다. - NaN 감지 가능: 기존의
indexOf()와 달리NaN값도 정확하게 찾아낼 수 있다는 장점이 있습니다.