배열에서 특정 요소가 있는지 찾아보고 싶을 때, ‘includes’ 기능을 사용할 수 있는데

예를 들어,

 

const target = ['가', '나', '다', '라', '마'];

const result = target.includes('나');

const result1 = target.includes('바');

console.log(result);

console.log(result1);

true

false

와 같이 나타나며 주어진 값이 배열 내부에 존재하면 ‘true’가 되고, 존재하지 않으면 ‘false’로 나타난다.

 

‘indexof’와 ‘lastIndexOf’ 기능을 사용하여 찾고자 하는 요소가 몇 번째 인덱스에 위치하는지도 알 수 있으며

이는

const target = ['나', '다', '라', '다', '라'];

const result0 = target.indexOf('다');

const result1 = target.lastIndexOf('라');

const result2 = target.indexOf('가');

console.log(result0);

console.log(result1);

console.log(result2);

1

4

-1

와 같이 나타날 수 있으며

‘const result0 = target.indexOf('다');’의 경우, ‘다’ 요소가 인덱스 1번에 위치하므로 값이 ‘1’로 나타나였고

‘const result1 = target.lastIndexOf('라');’의 경우 ‘라’ 요소가 2개 있지만, 뒤에서부터 검색하여 ‘4’의 값이 나타났으며

‘const result2 = target.indexOf('가');’ 의 경우 ‘가’ 요소가 존재하지 않으므로 ‘-1’로 값이 나타났다.

728x90

'Javascript' 카테고리의 다른 글

배열 메소드 응용하기  (1) 2024.12.22
배열 반복하기  (0) 2024.12.21
배열 메소드(수정, 조회)  (0) 2024.12.19
배열(Array)과 객체(Object)  (0) 2024.12.17
자바스크립트 중첩반복문과 별 찍기  (0) 2024.10.23