Dseok의 실전 예제로 웹개발 한방에 끝내기

웹개발, 혼자 하려니 막막하고 힘드시죠? 저 또한 그렇습니다. 힘든 웹개발... 실전 예제를 통해 함께 공부해요!!!!😁📕

Javascript

[Dseok의 코딩스터디] javascript / includes() / 자바스크립트 includes() / Array.prototype.includes()

Dseok 2023. 7. 29. 00:10
반응형
SMALL

오늘은 includes() 메소드에 대해 알아보려고 한다.

나중에 정리하려고 한 녀석인데 앞 포스팅에 간간히 등장하는 녀석이라 먼저 정리 해보고자 한다.

 

MDN의 설명은 이러하다.

includes()
메서드는 배열이 특정 요소를 포함하고 있는지 판별합니다.

오늘은 비교적 설명이 간단하다.

 

내가 이해한대로 설명을 조금 바꾸자면,

어떤 배열에서 내가 원하는 원소가 있는지 확인시켜준다.

이 문장으로 정리를 할 수 있어 보인다.

현재 고객(실사용자)들이 사용하기에는 브라우저 호환의 문제는 크게 있어보이진 않지만,

망할놈의 인터넷 익스플로러(IE)에서는 11버전까지 호환이 안되는 문제가 있다.

 

IE가 없어지기는 했지만...그래도 어디선가 살아 있을 IE를 위해 MDN에 있는 폴리필 코드를 이용하면 좋을 것 같다.

인터넷은 모든 사용자가 동일하고 평등하게 사용해야하니 IT개발자로서의 작은 윤리의식(?)을 생각해서 폴리필 코드를 블로그에 참고 하겠다.

 

if (!Array.prototype.includes) {
  Array.prototype.includes = function(searchElement, fromIndex) {
    if (this == null) {
      throw new TypeError('Array.prototype.includes called on null or undefined');
    }

    const array = Object(this);
    const len = array.length >>> 0;

    if (len === 0) {
      return false;
    }

    const n = fromIndex | 0;
    let k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);

    while (k < len) {
      if (array[k] === searchElement) {
        return true;
      }
      k++;
    }

    return false;
  };
}

위 코드를 따로 자바스크립트 파일로 만들어 html에 불러오기로 해서 사용하면 된다.

 

<head>
  <!-- 다른 meta 태그, 스타일시트 등 생략 -->

  <!-- includes() 폴리필 스크립트 -->
  <script src="./js/includes_method.js"></script>
</head>

잡다한 설명이 길었다.

 

바로 includes()메소드의 구문을 보자.

내가만든배열.includes(valueToFind[, fromIndex])

includes()메소드의 인자는

 

최대 2개의 인자를 받을 수 있다.

 

1. valueToFind라고 적혀 있는 부분에는 내가 찾고자하는 원소값을 넣는다.

2. fromIndex는 어디서부터 찾기를 시작할 것인가에 대한 인자인다. 음수로 입력이 가능하다.(음수로 사용하는 사람은 없기를 바란다.)

 

다음은 간단한 예시이다.

const array1 = [1, 2, 3];

console.log(array1.includes(2));
// Expected output: true

const pets = ['cat', 'dog', 'bat'];

console.log(pets.includes('cat'));
// Expected output: true

console.log(pets.includes('at'));
// Expected output: false

includes()는 불리언값, 즉 true, false로만 값을 내어준다.

true면 찾고자 하는 값이 있는 것, false면 찾고자 하는 값이 없는 것.

 

다음은 두번째 인자를 넣은 예시이다.

[1, 2, 3].includes(2);     // true
[1, 2, 3].includes(4);     // false
[1, 2, 3].includes(3, 3);  // false
[1, 2, 3].includes(3, -1); // true
[1, 2, NaN].includes(NaN); // true

음수... 사용하지 말자...

 

자바스크립트 includes()메소드의 실제 어떻게 활용 되고 있는지 몇가지 예시로 알아보자.

 

1. 검색 기능 구현

2. 중복 요소 확인

3. 특정 값의 인덱스 확인

4. 조건을 만족하는 요소 확인

5. 요소의 존재 여부 확인

 

이 예시 중 조건을 만족하는 요소 확인의 예시를 보자.

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="keywords" content="basic" />
    <meta name="description" content="basic" />
    <link rel="shortcut icon" href="" />
    <link rel="stylesheet" href="./css/reset.css">
    <link rel="stylesheet" href="./css/index.css">
    <title>basic</title>
</head>
<body>
    <h1>Includes 메소드 예시</h1>
    <div class="box">
        <label for="searchInput">과일 검색:</label>
        <input type="text" id="searchInput">
        <button id="searchButton">검색</button>
        <p class="p_txt">과일의 예시는 '사과', '바나나', '오렌지', '포도'로만 데이터가 들어가 있습니다.</p>
    </div>
    <div id="result"></div>
    <script src="./js/jquery-3.6.0.min.js"></script>
    <script src="./js/index.js"></script>
</body>
</html>

html코드이다.

 

@charset "UTF-8";
body {
  font-family: Arial, sans-serif;
  margin: 20px;
}

h1 {
  text-align: center;
}

.box {
  margin: 20px auto 0;
  width: 50%;
}

label {
  margin-right: 5px;
}

input[type="text"] {
  padding: 5px;
}

.p_txt{
  font-size: 13px;
  margin-top: 10px;
}

button {
  padding: 5px 10px;
}

귀찮아서 대충 css 코드를 끄적여봤다.

 

const fruits = ['사과', '바나나', '오렌지', '포도'];

document.getElementById('searchButton').addEventListener('click', () => {
  const searchInput = document.getElementById('searchInput').value;
  const resultDiv = document.getElementById('result');

  // includes() 메소드를 사용하여 입력한 과일이 배열에 포함되어 있는지 확인
  const isFruitFound = fruits.includes(searchInput);

  if (isFruitFound) {
    // 입력한 과일이 배열에 포함되어 있으면 결과를 보여줌
    resultDiv.innerHTML = `${searchInput}는(은) 과일입니다!`;
  } else {
    // 입력한 과일이 배열에 포함되어 있지 않으면 결과를 보여줌
    resultDiv.innerHTML = `${searchInput}는(은) 과일이 아닙니다.`;
  }
});

자바스크립트 예시 코드이다.

 

재미있게 잘 가져다 써줘라.

반응형
LIST