[JavaScript] 배열 내장 함수

semi·2021년 1월 28일
0

JavaScript

목록 보기
1/2

forEach

//1.forEach
const arrayForEach = ['하나', '둘', '셋', '넷'];
//for문으로 출력을 구현할 경우
for (let i = 0; i < arrayForEach.length; i++) {
  console.log(arrayForEach[i]);
}
//forEach문으로 출력 구현
arrayForEach.forEach((number) => {
  console.log(number);
});

forEach 함수의 파라미터
=> 각 원소에 대해 처리하고 싶은 코드를 함수로 넣는다.
위 예시에서 number은 listForEach의 각 원소를 가리킨다.

map(중요!)

배열 안의 각 원소를 변환 할 때 사용하며 새로운 배열을 반환한다.

//2.map
const arrayMap = [1, 2, 3, 4, 5, 6, 7];
//for문 사용해서 새로운 배열 반환
const resultFor = [];
for (let i = 0; i < arrayMap.length; i++) {
  resultFor.push(arrayMap[i] * 3);
}
console.log(resultFor);
//map사용해서 새로운 배열 반환
const resultMap = arrayMap.map((number) => number * 3);
console.log(resultMap);

map 함수의 파라미터
=> 변화를 주는 함수를 전달한다.

indexOf

배열 안에 있는 값이 숫자, 문자열 또는 boolean일 때,
원하는 항목이 몇번째 원소인지 찾아준다.
즉, 배열에서 특정 원소의 index를 반환한다.

//3.indexOf
const arrayindexOf = ['하나', '둘', '셋', '넷'];
const index = arrayindexOf.indexOf('둘');
console.log(index);

findIndex

배열 안에 있는 값이 객체 또는 배열일때 index를 반환한다.

//4.findIndex
const arrayFindeIndex = [
  {
    id: 1,
    text: '하나',
    boolean: true,
  },
  {
    id: 2,
    text: '둘',
    boolean: true,
  },
  {
    id: 3,
    text: '셋',
    boolean: true,
  },
  {
    id: 4,
    text: '넷',
    boolean: false,
  },
];
const indexFindIndex = arrayFindeIndex.findIndex((obj) => obj.id === 3);
console.log(indexFindIndex);

find

찾아낸 값 자체를 반환한다.

//5.find
const arrayFind = [
  {
    id: 1,
    text: '하나',
    boolean: true,
  },
  {
    id: 2,
    text: '둘',
    boolean: true,
  },
  {
    id: 3,
    text: '셋',
    boolean: true,
  },
  {
    id: 4,
    text: '넷',
    boolean: false,
  },
];
const indexFind = arrayFind.find((obj) => obj.id === 3);
console.log(indexFind);

결과

filter(중요!)

배열에서 특정 조건을 만족하는 값들만 추출하여 새로운 배열을 반환한다.

//6.filter
const arrayFilter = [
  {
    id: 1,
    text: '하나',
    boolean: true,
  },
  {
    id: 2,
    text: '둘',
    boolean: true,
  },
  {
    id: 3,
    text: '셋',
    boolean: true,
  },
  {
    id: 4,
    text: '넷',
    boolean: false,
  },
];
const resultFilter = arrayFilter.filter((obj) => obj.boolean === true);
console.log(resultFilter);

결과

splice

배열에서 특정 항목을 제거할 때 사용한다.

splice(1,2)에서
첫 번째 파라미터
=> 어떤 인덱스부터 지울지
두 번째 파라미터
=> 지울 항목의 갯수

slice

배열을 잘라낼 때 사용하며 기존의 배열은 건들지 않고 새로운 배열을 반환한다.

slice(1,2)에서
첫 번째 파라미터
=> 어떤 인덱스부터 자를지
두 번째 파라미터
=> 어디까지 자를지

shift

첫 번째 원소를 배열에서 추출하고 해당 배열에서 추출한 원소는 없어진다.

unshift

shift와 반대로 배열의 맨 앞에 새 원소를 추가한다.

pop

마지막 원소를 배열에서 추출하며 해당 배열에서 추출한 원소는 없어진다.

push

pop과 반대로 배열의 맨 마지막에 새 항목을 추가한다.

concat

여러개의 배열을 하나의 배열로 합쳐서 새로운 배열을 반환한다.

join

배열 안의 값들을 문자열 형태로 합친다.

reduce(중요!!)

const result7Average = result7.reduce((accumulator, current, index, array) => {
  if (index === array.length - 1) return accumulator / array.length;
  return accumulator + current;
}, 0);

reduce 콜백 함수의 4가지 파라미터
=> 누적값, 현재값, 현재 index, 현재 배열
초기값 설정해줘야된다!

참고

벨로퍼트와 함께하는 모던 자바스크립트

0개의 댓글