[JavaScript] replaceAll, findIndex, filter

김서진·2024년 2월 15일
post-thumbnail

Array.prototype.filter()

주어진 배열의 일부에 대한 얕은 복사본을 생성하고, 주어진 배열에서 제공된 함수에 의해 구현된 테스트를 통과한 요소로만 필터링 한다.

// filter(callbackFn)
// filter(callbackFn, thisArg)

const words = ['', 'hello', '', 'world']

console.log(words.filter(v => v)) // Array ["hello", "world"]

// filter(v => v)에서 v는 배열의 각 요소를 나타내고, 콜백 함수는 각 요소 v가 true로 평가되는지 여부를 확인한다. 
빈 문자열인 경우 false로 간주되어 filter에 의해 제거. 최종적으로 빈 문자열을 제거한 배열이 반환된다.

빈 문자열이 제거되는줄 몰랐다.

String.prototype.replaceAll()

replaceAll() 메서드는 pattern의 모든 일치 항목이 replacement로 대체된 새 문자열을 반환한다. pattern은 문자열이나 RegExp일 수 있다. 원래 문자열은 변경되지 않는다.

// replaceAll(pattern, replacement)

const str = 'bbbbb'

console.log(str.replaceAll('b', 'a')); // 'aaaaa'

Array.prototype.findIndex()

주어진 판별 함수를 만족하는 배열의 첫 번째 요소에 대한 인덱스를 반환하고. 만족하는 요소가 없으면 -1 반환.

// findIndex(callbackFn)
// findIndex(callbackFn, thisArg)

const arr = [1, 10, -8, -50, 20];

const negative = (v) => v < 0;

console.log(arr.findIndex(negative)); // 2

참고자료

0개의 댓글