Array - includes(), indexOf()

sorikikikim·2023년 5월 12일

Javascript-Array

목록 보기
4/5

Array.prototype.includes()

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

arr.includes(valueToFind[, fromIndex])
arr에 valueToFind 요소가 있으면 true, 없으면 false를 반환한다. fromIndex는 요소를 찾기 시작할 인덱스 값으로 0이 기본값이다.

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()와 비슷한 함수로는 indexOf()가 있다.

Array.prototype.indexOf()

arr.indexOf(searchElement[, fromIndex])
indexOf() 메서드는 배열에서 지정된 요소를 찾을 수 있는 첫 번째 인덱스를 반환하고 존재하지 않으면 -1을 반환한다.

const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];

console.log(beasts.indexOf('bison'));
// Expected output: 1

// Start from index 2
console.log(beasts.indexOf('bison', 2));
// Expected output: 4

console.log(beasts.indexOf('giraffe'));
// Expected output: -1

var array = [2, 9, 9];
array.indexOf(2);     // 0
array.indexOf(7);     // -1
array.indexOf(9, 2);  // 2
array.indexOf(2, -1); // -1
array.indexOf(2, -3); // 0

0개의 댓글