3/16 JS 메소드

Clear·2023년 3월 16일
0

Daily Posting

목록 보기
2/27

reduce: 배열의 각 요소에 대해 콜백 함수를 실행하고 누적 값을 계산하여 단일 결과 값을 반환합니다

const sum = [1, 2, 3].reduce((acc, curr) => acc + curr, 0);
console.log(sum); // 6

indexOf: 배열에서 특정 요소를 찾아 첫 번째 인덱스를 반환합니다. 찾지 못하면 -1을 반환합니다

const index = [1, 2, 3].indexOf(3);
console.log(index); // 2

length: 배열의 요소 수를 반환합니다

const length = [1, 2, 3].length;
console.log(length); // 3

fill: 배열의 모든 요소를 정적인 값으로 채웁니다

const filled = new Array(3).fill(0);
console.log(filled); // [0, 0, 0]

sort: 배열의 요소를 정렬하고 정렬된 배열을 반환합니다

const arr = [3, 2, 1];
const ascending = arr.sort((a, b) => a - b);
console.log(ascending); // [1, 2, 3]
const descending = arr.sort((a, b) => b - a);
console.log(descending); // [3, 2, 1]

from: 유사 배열 객체나 반복 가능한 객체로부터 새로운 얕은 복사된 배열 객체를 만듭니다

const copied = Array.from([1, 2, 3]);
console.log(copied); // [1, 2, 3]

map: 배열의 각 요소에 대해 제공된 함수를 호출한 결과를 모은 새로운 배열을 반환합니다

const mapped = [1, 2, 3].map(x => x * 2);
console.log(mapped); // [2, 4, 6]

filter: 제공된 함수에 통과한 배열의 모든 요소를 모은 새로운 배열을 반환합니다

const filtered = [1, 2, 3].filter(x => x > 1);
console.log(filtered); // [2, 3]

split: 지정된 구분자를 기준으로 문자열을 분할하고 각 하위 문자열의 배열을 반환합니다

const split = "hello world".split(' ');
console.log(split); // ["hello", "world"]

reverse: 배열의 순서를 뒤집습니다

const reversed = [1, 2, 3].reverse();
console.log(reversed); // [3, 2, 1]

join: 배열의 모든 요소를 연결하여 단일 문자열을 반환합니다

const joined = ['hello', 'world'].join(' ');
console.log(joined); // "hello world"

match: 문자열에서 정규 표현식과 일치하는 항목의 배열을 반환합니다

const matched = "hello world".match(/[aeiou]/gi);
console.log(matched); // ["e", "o", "o"]

0개의 댓글