✅ String.prototype.indexOf()
- string객체에서 주어진 값과 일치하는 첫 번째 인덱스를 반환
- 일치하지 않으면 -1 반환
const paragraph = 'I like banana. Do you like banana?';
const searchTerm = 'banana';
const indexOfFirst = paragraph.indexOf(searchTerm);
console.log(`The index of the first "${searchTerm}" from the beginning is "${indexOfFirst}");
// "The index of the first "banana" from the beginning is 7"
console.log(`The index of the second "${searchTerm}" is "${paragraph.indexOf(searchTerm, (indexOfFirst + 1))}")`;
// "The index of the second "banana" is 27"
✅ Array.prototype.indexOf()
- 배열에서 지정된 요소를 찾을 수 있는 첫 번째 인덱스를 반환
- 존재하지 않으면 -1을 반환
const alpha = ['a', 'b', 'c', 'd', 'c'];
// indexOf는 가장 먼저 찾은 일치하는 값의 인덱스를 반환한다.
console.log(alpha.indexOf('c'); // 2
// 탐색을 시작할 index번호를 지정할 수 있다.
console.log(alpha.indexOf('c', 2)); // 4
// 해당 값이 없는 경우에는 -1을 반환한다.
console.log(alpha.indexOf('e')); // -1
출처 :
mdn 공식문서 - String.prototype.indexOf()
mdn 공식문서 - Array.prototype.indexOf()