Array APIs - indexOf(), lastIndexOf(), includes()

2022. 10. 5. 13:48Javascript

이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다.

반응형

indexOf : 특정한 요소의 위치를 찾을 때

indexOf(searchElement: T, fromIndex?: number): number;
/**
 * Returns the index of the first occurrence of a value in an array.
 * @param searchElement The value to locate in the array.
 * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.
 */
//특정한 요소의 위치를 찾을 때
const bread = ['🍞', '🥖', '🥐', '🥨'];
console.log(bread.indexOf('🥖')); //1
console.log(bread.indexOf('🍕')); //-1

 

lastIndexOf : 특정한 요소의 위치를 뒤에서부터 찾을 때

lastIndexOf(searchElement: T, fromIndex?: number): number;
/**
 * Returns the index of the last occurrence of a specified value in an array.
 * @param searchElement The value to locate in the array.
 * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array.
 */
//특정한 요소의 위치를 뒤에서 부터 찾을 때
const bread = ['🍞', '🥖', '🥐', '🥨'];
console.log(bread.lastIndexOf('🥖')); //1
console.log(bread.lastIndexOf('🍕')); //-1

 

includes : 배열 안에 특정한 요소가 있는지 체크

includes(searchElement: T, fromIndex?: number): boolean;
/**
 * Determines whether an array includes a certain element, returning true or false as appropriate.
 * @param searchElement The element to search for.
 * @param fromIndex The position in this array at which to begin searching for searchElement.
 */
//배열 안에 특정한 요소가 있는지 체크
const bread = ['🍞', '🥖', '🥐', '🥨'];
console.log(bread.includes('🥐')); //true
console.log(bread.includes('🍕')); //false

 

반응형