Computer >> 컴퓨터 >  >> 프로그래밍 >> JavaScript

JavaScript 배열 includes() 메서드 완벽 가이드 – 사용법과 예제

JavaScript array.includes() 메서드란?

JavaScript의 array.includes() 메서드는 배열에 특정 요소가 포함되어 있는지 여부를 확인할 때 사용하는 메서드입니다. 요소가 배열 안에 존재하면 true, 존재하지 않으면 false를 반환하므로, 조건문과 함께 활용하면 매우 유용합니다.

기본 문법

arr.includes(searchElement[, fromIndex])
  • searchElement: 배열에서 찾고자 하는 요소 (필수)
  • fromIndex: 검색을 시작할 인덱스 위치 (선택 사항, 기본값은 0)

참고로 includes()는 대소문자를 구분하며, NaN 값도 정확하게 감지할 수 있다는 점에서 indexOf()보다 직관적이라는 장점이 있습니다.

예제 코드

다음은 array.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>

코드 설명

  1. 배열 arr에는 다섯 개의 동물 이름이 담겨 있습니다: ["cow", "bull", "lion", "tiger", "sheep"]
  2. 페이지가 로드되면 .sample 영역에 배열 전체가 화면에 표시됩니다.
  3. 버튼을 클릭하면 arr.includes("lion")이 실행되어 배열에 "lion"이 있는지 검사하고, 그 결과(true 또는 false)가 화면에 출력됩니다.

실행 결과

페이지를 처음 열면 아래와 같이 배열의 요소들이 화면에 나타납니다.

JavaScript 배열 includes() 메서드 완벽 가이드 – 사용법과 예제

이후 “CLICK HERE” 버튼을 클릭하면 다음과 같이 검사 결과가 표시됩니다.

JavaScript 배열 includes() 메서드 완벽 가이드 – 사용법과 예제

배열에 "lion"이 포함되어 있으므로 true가 출력되는 것을 확인할 수 있습니다. 이처럼 includes() 메서드를 사용하면 복잡한 반복문 없이 한 줄의 코드로 배열 내 요소 존재 여부를 손쉽게 판별할 수 있습니다.